i want to create one tab bar from storyboard and i create it but when click on tab bar at that time image is not showing and some images i want tab bar like
and i got this
When i click on any tab bar item its display like
Here is my code that i use in profile view controller
class ProfileViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
UIApplication.shared.statusBarStyle = .default
self.tabBarController?.tabBar.isHidden = false
UITabBar.appearance().tintColor = UIColor.init(patternImage: UIImage.init(named: "ic_home_tab_profile_sel.png")!)
// Do any additional setup after loading the view.
}
}
Any help can be appreciate .
Thank You in advance.
I suggest to use ESTabBarControllerExample https://github.com/eggswift/ESTabBarController to making that kind of custom TabbarController.First Download the ESTabbarControllerExample from github. We need to use some class letter on. Let me explain how to use step by step:
First Install CocoaPods
1 Open terminal and cd ~ to your project directory
2 Run the command - pod init
3 Your podfile should be use with - pod
"ESTabBarController-swift" and save it
4 And install it with command pod install
Open project file of .xcworkspace extension
1 In project we need to add Content all swift class and pop.framework
2 Don't add pop.framework using add File to. you must be add from Framework and add Others.
3 In Content folder's all file import ESTabBarController_swift
StoryBord Stuff
1 Add navigation Controller ane also add ExampleNavigationController from the example code of EST demo. (You can add your own too) but make sure you set its Class of navigation custom swift class.
Code Stuff at AppDelegate.swift
You need to do following code in side didFinishLaunchingWithOptions
let tabBarController = ESTabBarController()
tabBarController.delegate = self
tabBarController.title = "Irregularity"
tabBarController.tabBar.shadowImage = UIImage(named: "transparent")
tabBarController.tabBar.backgroundImage = UIImage(named: "background_dark")
tabBarController.shouldHijackHandler = {
tabbarController, viewController, index in
if index == 2 {
return true
}
return false
}
tabBarController.didHijackHandler = {
[weak tabBarController] tabbarController, viewController, index in
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
let alertController = UIAlertController.init(title: nil, message: nil, preferredStyle: .actionSheet)
let takePhotoAction = UIAlertAction(title: "Take a photo", style: .default, handler: nil)
alertController.addAction(takePhotoAction)
let selectFromAlbumAction = UIAlertAction(title: "Select from album", style: .default, handler: nil)
alertController.addAction(selectFromAlbumAction)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alertController.addAction(cancelAction)
tabBarController?.present(alertController, animated: true, completion: nil)
}
}
let v1 = ExampleViewController()
let v2 = ExampleViewController()
let v3 = ExampleViewController()
let v4 = ExampleViewController()
let v5 = ExampleViewController()
v1.tabBarItem = ESTabBarItem.init(ExampleIrregularityBasicContentView(), title: "Home", image: UIImage(named: "home"), selectedImage: UIImage(named: "home_1"))
v2.tabBarItem = ESTabBarItem.init(ExampleIrregularityBasicContentView(), title: "Find", image: UIImage(named: "find"), selectedImage: UIImage(named: "find_1"))
v3.tabBarItem = ESTabBarItem.init(ExampleIrregularityContentView(), title: nil, image: UIImage(named: "photo_verybig"), selectedImage: UIImage(named: "photo_verybig"))
v4.tabBarItem = ESTabBarItem.init(ExampleIrregularityBasicContentView(), title: "Favor", image: UIImage(named: "favor"), selectedImage: UIImage(named: "favor_1"))
v5.tabBarItem = ESTabBarItem.init(ExampleIrregularityBasicContentView(), title: "Me", image: UIImage(named: "me"), selectedImage: UIImage(named: "me_1"))
tabBarController.viewControllers = [v1, v2, v3, v4, v5]
let navigationController = ExampleNavigationController.init(rootViewController: tabBarController)
tabBarController.title = "Example"
self.window?.rootViewController = navigationController
return true
Add Images for Tabbar items and other that you want to use for in Assets.
Hope that helps for you.
Sample Project: https://github.com/nitingohel/CustomTabCenterBig
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I am trying to implement based on ActionSheet button click to show selected button title on main viewcontroller UILabel. Here, below code I am using but the label title not updating based on actionsheet button click.
The issue happening by for loop execution. UILabel.text not changing before last For Loop execution. how to handle and fix it?
ActionSheet
#IBAction func ClickAction(_ sender: Any) {
let actionSheetAlertController: UIAlertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
for title in self.titleData {
let action = UIAlertAction(title: title.status, style: .default) { (action) in
print("Title: \(title.status)")
print("Title: \(title.id)")
self.resultTitle.text = title.status // not updating here.
let icon = UIImage.init(named: title.icon)
action.setValue(icon, forKey: "image")
action.setValue(CATextLayerAlignmentMode.left, forKey: "titleTextAlignment")
actionSheetAlertController.addAction(action)
}
let cancelActionButton = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
actionSheetAlertController.addAction(cancelActionButton)
self.present(actionSheetAlertController, animated: true, completion: nil)
}
Getting Output
Your issue not occured in my machine. Please restart your machine, maybe problem will resolve.
You need to make the checks with action title not with the id. So, here is you solution that is working fine:
struct ActionOption {
var id: String
var title: String
var icon: UIImage?
static func getAll() -> [ActionOption] {
let titleData = ["Red", "Green", "Yellow"]
var all: [ActionOption] = []
for (idx, ttl) in titleData.enumerated() {
all.append(ActionOption(id: "\(idx)", title: ttl, icon: nil))
}
return all
}
}
class ViewController: UIViewController {
#IBOutlet weak var imageView: UIImageView!
var titleData: [ActionOption] = []
override func viewDidLoad() {
super.viewDidLoad()
self.titleData = ActionOption.getAll()
}
#IBAction func changeAction(_ sender: Any) {
let actionSheetAlertController: UIAlertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
for title in self.titleData {
let action = UIAlertAction(title: title.title, style: .default) { (action) in
switch (action.title ?? "") { // you need to vhange your code here
case "Red" :
self.imageView.backgroundColor = UIColor.red
case "Green" :
self.imageView.backgroundColor = UIColor.green
case "Yellow" :
self.imageView.backgroundColor = UIColor.yellow
default : self.imageView.backgroundColor = UIColor.black
}
}
action.setValue(title.icon, forKey: "image")
action.setValue(CATextLayerAlignmentMode.left, forKey: "titleTextAlignment")
actionSheetAlertController.addAction(action)
}
let cancelActionButton = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
actionSheetAlertController.addAction(cancelActionButton)
self.present(actionSheetAlertController, animated: true, completion: nil)
}
}
You need to make some changes in you switch statement, use the parameter closure for deciding the desired action to perform. As these closure will call when the action being perform and that time title for loop object will not be present/available for being used.
Result As of Code:
Just put self.resultTitle.text = title.status inside DispatchQueue.main.async { }
#IBAction func ClickAction(_ sender: Any) {
let actionSheetAlertController: UIAlertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
for title in self.titleData { // I thik this is the plm
let action = UIAlertAction(title: title.status, style: .default) { (action) in
print("Title: \(title.status)")
print("Title: \(title.id)")
DispatchQueue.main.async {
self.resultTitle.text = title.status
}
}
let icon = UIImage.init(named: title.icon)
action.setValue(icon, forKey: "image")
action.setValue(CATextLayerAlignmentMode.left, forKey: "titleTextAlignment")
actionSheetAlertController.addAction(action)
}
let cancelActionButton = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
actionSheetAlertController.addAction(cancelActionButton)
self.present(actionSheetAlertController, animated: true, completion: nil)
}
I have issues. After language changing, I want to restart my application.
So I want to get an alert message with the text "Do you want to restart app to change language?" "Yes" "No"
And if the user presses YES, how can I restart the app?
My solution:
let alertController = UIAlertController(title: "Language".localized(), message: "To changing language you need to restart application, do you want to restart?".localized(), preferredStyle: .alert)
let okAction = UIAlertAction(title: "Yes".localized(), style: UIAlertActionStyle.default) {
UIAlertAction in
NSLog("OK Pressed")
exit(0)
}
let cancelAction = UIAlertAction(title: "Restart later".localized(), style: UIAlertActionStyle.cancel) {
UIAlertAction in
NSLog("Cancel Pressed")
}
alertController.addAction(okAction)
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
After the app will close, the user will manually start the app.
You cannot restart an iOS app. One thing you could do is to pop to your rootViewController.
func restartApplication () {
let viewController = LaunchScreenViewController()
let navCtrl = UINavigationController(rootViewController: viewController)
guard
let window = UIApplication.shared.keyWindow,
let rootViewController = window.rootViewController
else {
return
}
navCtrl.view.frame = rootViewController.view.frame
navCtrl.view.layoutIfNeeded()
UIView.transition(with: window, duration: 0.3, options: .transitionCrossDissolve, animations: {
window.rootViewController = navCtrl
})
}
In one of my apps, I needed to restart. I wrapped all of the loading logic into a LaunchScreenViewController. Above is the piece of code for "restarting the app".
It's not perfect, but I solved this by sending a timed local notification just before exiting the application. Then the user only needs to click on the notification to restart the app so they don't need to look for the app to relaunch it. I also suggest displaying an alert informing the user of the restart:
import UserNotifications
import Darwin // needed for exit(0)
struct RestartAppView: View {
#State private var showConfirm = false
var body: some View {
VStack {
Button(action: {
self.showConfirm = true
}) {
Text("Update Configuration")
}
}.alert(isPresented: $showConfirm, content: { confirmChange })
}
var confirmChange: Alert {
Alert(title: Text("Change Configuration?"), message: Text("This application needs to restart to update the configuration.\n\nDo you want to restart the application?"),
primaryButton: .default (Text("Yes")) {
restartApplication()
},
secondaryButton: .cancel(Text("No"))
)
}
func restartApplication(){
var localUserInfo: [AnyHashable : Any] = [:]
localUserInfo["pushType"] = "restart"
let content = UNMutableNotificationContent()
content.title = "Configuration Update Complete"
content.body = "Tap to reopen the application"
content.sound = UNNotificationSound.default
content.userInfo = localUserInfo
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 0.5, repeats: false)
let identifier = "com.domain.restart"
let request = UNNotificationRequest.init(identifier: identifier, content: content, trigger: trigger)
let center = UNUserNotificationCenter.current()
center.add(request)
exit(0)
}
}
You can change your root controller and don't need to restart it. Just change the root view controller or update or refresh or recall the root view controller:
let alertController = UIAlertController(title: "Language".localized(), message: "To change language you need to restart the application. Do you want to restart?".localized(), preferredStyle: .alert)
let okAction = UIAlertAction(title: "Yes".localized(), style: UIAlertActionStyle.default) {
UIAlertAction in
// Change update / refresh rootview controller here...
}
You can add to AppDelegate
func resetApp() {
UIApplication.shared.windows[0].rootViewController = UIStoryboard(
name: "Main",
bundle: nil
).instantiateInitialViewController()
}
Call this function where you want
let appDelegate = AppDelegate()
appDelegate.startWith()
Add this to your viewDidLoad for starting the viewcontroller (VC):
override func viewDidLoad() {
super.viewDidLoad()
// Make dismiss for all VC that was presented from this start VC
self.children.forEach({vc in
print("Dismiss \(vc.description)")
vc.dismiss(animated: false, completion: nil)
})
// ....
}
And in the restart initiator:
// ...
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "startVC")
self.present(vc, animated: false, completion: nil)
How to make an Instagram-like tab like this?
Instagram's tab
Do I need to make more than one UIViewControllers or make something on one UIViewController?
Thanks in advance for any help!
I suggest to use ESTabBarControllerExample https://github.com/eggswift/ESTabBarController to making that kind of custom TabbarController.First Download the ESTabbarControllerExample from github. We need to use some class letter on. Let me explain how to use step by step:
First Install CocoaPods
1 Open terminal and cd ~ to your project directory
2 Run the command - pod init
3 Your podfile should be use with - pod
"ESTabBarController-swift" and save it
4 And install it with command pod install
Open project file of .xcworkspace extension
1 In project we need to add Content all swift class and pop.framework
2 Don't add pop.framework using add File to. you must be add from Framework and add Others.
3 In Content folder's all file import ESTabBarController_swift
StoryBord Stuff
1 Add navigation Controller ane also add ExampleNavigationController from the example code of EST demo. (You can add your own too) but make sure you set its Class of navigation custom swift class.
Code Stuff at AppDelegate.swift
You need to do following code in side didFinishLaunchingWithOptions
let tabBarController = ESTabBarController()
tabBarController.delegate = self
tabBarController.title = "Irregularity"
tabBarController.tabBar.shadowImage = UIImage(named: "transparent")
tabBarController.tabBar.backgroundImage = UIImage(named: "background_dark")
tabBarController.shouldHijackHandler = {
tabbarController, viewController, index in
if index == 2 {
return true
}
return false
}
tabBarController.didHijackHandler = {
[weak tabBarController] tabbarController, viewController, index in
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
let alertController = UIAlertController.init(title: nil, message: nil, preferredStyle: .actionSheet)
let takePhotoAction = UIAlertAction(title: "Take a photo", style: .default, handler: nil)
alertController.addAction(takePhotoAction)
let selectFromAlbumAction = UIAlertAction(title: "Select from album", style: .default, handler: nil)
alertController.addAction(selectFromAlbumAction)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alertController.addAction(cancelAction)
tabBarController?.present(alertController, animated: true, completion: nil)
}
}
let v1 = ExampleViewController()
let v2 = ExampleViewController()
let v3 = ExampleViewController()
let v4 = ExampleViewController()
let v5 = ExampleViewController()
v1.tabBarItem = ESTabBarItem.init(ExampleIrregularityBasicContentView(), title: "Home", image: UIImage(named: "home"), selectedImage: UIImage(named: "home_1"))
v2.tabBarItem = ESTabBarItem.init(ExampleIrregularityBasicContentView(), title: "Find", image: UIImage(named: "find"), selectedImage: UIImage(named: "find_1"))
v3.tabBarItem = ESTabBarItem.init(ExampleIrregularityContentView(), title: nil, image: UIImage(named: "photo_verybig"), selectedImage: UIImage(named: "photo_verybig"))
v4.tabBarItem = ESTabBarItem.init(ExampleIrregularityBasicContentView(), title: "Favor", image: UIImage(named: "favor"), selectedImage: UIImage(named: "favor_1"))
v5.tabBarItem = ESTabBarItem.init(ExampleIrregularityBasicContentView(), title: "Me", image: UIImage(named: "me"), selectedImage: UIImage(named: "me_1"))
tabBarController.viewControllers = [v1, v2, v3, v4, v5]
let navigationController = ExampleNavigationController.init(rootViewController: tabBarController)
tabBarController.title = "Example"
self.window?.rootViewController = navigationController
return true
Add Images for Tabbar items and other that you want to use for in Assets.
Hope that helps for you.
Sample Project: https://github.com/nitingohel/CustomTabCenterBig
// The quick actions
var previewActions:[UIPreviewActionItem] {
let item1 = UIPreviewAction(title: "Share", style: .default) { (action:UIPreviewAction, vc:UIViewController) -> Void in
self.shareAction()
print("Shared")
}
return [item1]
}
func shareAction(){
// text, image to share
let textToShare = self.selectedLabel ?? ""
let image = self.selectedImage
let subtitleToShare = self.selectedSubtitleLabel ?? ""
// set up activity view controller
let activityViewController = UIActivityViewController(activityItems: [textToShare,image,subtitleToShare], applicationActivities: nil)
// present the view controller
// let vc:UIViewController = (self.view.window?.rootViewController)!
self.present(activityViewController, animated: true, completion: nil)
} ** AT this point its showing up the error "Warning: Attempt to present <UIActivityViewController: 0x7fe9e962bc90> on <Project Name.[1]PreviewViewController: 0x7fe9e941e4a0> whose view is not in the window hierarchy!"and not performing the action**
[Check the image for the clear picture ]
[1]: https://i.stack.imgur.com/JKZEP.jpg
What needs to be done? where am going wrong? can someone please help me?
I am new to swift and I have followed some tutorial in alert view lesson. I want to add function like call another viewcontroller whenever the alert's button is clicked but i dont know how. so pls help me
func showAlertController(){
var title : String = "hi!"
var message : String = NSLocalizedString("Are you feeling well? ", comment:"")
let cancelButtonTitle = NSLocalizedString("No", comment:"")
let otherButtonTitle = NSLocalizedString("Yes", comment:"")
let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: cancelButtonTitle, style: .Cancel){
action in NSLog("No!!!!")
}
let otherAction = UIAlertAction(title: otherButtonTitle, style: .Default){
action in NSLog("welcome!!! hello back")
}
alertController.addAction(cancelAction)
alertController.addAction(otherAction)
presentViewController(alertController, animated: true, completion: nil)
}
Try this code:
let cancelAction = UIAlertAction(title: cancelButtonTitle, style: .Cancel){
action in NSLog("No!!!!")
let View2 = self.storyboard?.instantiateViewControllerWithIdentifier("View2") as TwoViewController
self.navigationController?.pushViewController(View2, animated: true)
}
and also select your existing view controller and then From the drop down menu select Edit>Embed in > Navigation Controller.
After that add a new view controller and create a new Cocoa Class and name it TwoViewController SubClass of UIViewController.
After that select your new ViewController and Customise it this way from Identity Inspector
May be this can help you.