pushViewController not working properly - ios

I've got a SidebarMenueController which is my entry point after starting the app.
Within there i've got a NavigationController embedded with a sidebar (slide out) menue. With sideBarDidSelectButtonAtIndex i catch which view, which should be loaded inside the NavigationController. When selecting an entry in the sidebar menue i want to push to another view.
Via printing (into the console) the selected menue entry, i can confirm that the selection is definitely working. But the pushViewController function is not loading the desired view.
I'm using no storyboard!
Any suggestions on how to fix this?
import UIKit
class SideBarMenueController: UIViewController, SideBarDelegate {
var sideBar:SideBar = SideBar()
lazy var menueButton: UIButton = {
let button = UIButton()
button.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
button.backgroundColor = UIColor.clear
button.setImage(#imageLiteral(resourceName: "MenueIcon"), for: UIControlState.normal)
button.addTarget(self, action: #selector(didSelectMenueButton), for: UIControlEvents.touchUpInside)
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
let layout = UICollectionViewFlowLayout()
let sideBarMenue = UINavigationController(rootViewController:FirstViewController(collectionViewLayout: layout))
self.addChildViewController(sideBarMenue)
sideBarMenue.view.frame = self.view.bounds
self.view.addSubview(sideBarMenue.view)
UINavigationBar.appearance().barTintColor = UIColor(red: 70/255, green: 174/255, blue: 253/255, alpha: 1)
let titleAttributes = [
NSFontAttributeName: UIFont.systemFont(ofSize: 20, weight: UIFontWeightBold),
NSForegroundColorAttributeName: UIColor.white
]
UINavigationBar.appearance().titleTextAttributes = titleAttributes
UINavigationBar.appearance().tintColor = UIColor.white
let NavigationMenueButton = UIBarButtonItem(customView: menueButton)
navigationItem.leftBarButtonItem = NavigationMenueButton
sideBar = SideBar(sourceView: self.view, menuItems: ["feed now", "feed times", "cats", "device status", "device setup", "about app"])
sideBar.delegate = self
}
func didSelectMenueButton() {
let layout = UICollectionViewFlowLayout()
let controller = FeedTimesController(collectionViewLayout: layout)
navigationController?.pushViewController(controller, animated: true)
}
func sideBarDidSelectButtonAtIndex(_ index: Int) {
if index == 0{
let controller = FirstViewController()
navigationController?.pushViewController(controller, animated: true)
print("touched index 0")
} else if index == 1{
let layout = UICollectionViewFlowLayout()
let controller = SecondViewController(collectionViewLayout: layout)
navigationController?.pushViewController(controller, animated: true)
print("touched index 1")
} else if index == 2{
let layout = UICollectionViewFlowLayout()
let controller = ThirdViewController(collectionViewLayout: layout)
navigationController?.pushViewController(controller, animated: true)
print("touched index 2")
} else if index == 3{
print("touched index 3")
} else if index == 4{
print("touched index 4")
} else if index == 5{
print("touched index 5")
}
sideBar.showSideBar(false)
}
}

It looks like you are creating a NavigationController with:
let sideBarMenue = UINavigationController(rootViewController:FirstViewController(collectionViewLayout: layout))
Then you are adding that controller's view as a subview to self.view:
self.view.addSubview(sideBarMenue.view)
But then later, in didSelect, you are trying to access (implied) self.navigationController:
navigationController?.pushViewController(controller, animated: true)
Not sure, but it looks like you want to access the nav controller via:
sideBar.navigationController
Without seeing the code / library you're using for SideBar, this may or may not resolve your issue.

Related

UINavigationBar Large Title doesn't appear when scroll view up

I have implemented a feature, when you press on a UITabBar icon and viewController1 scrolls up using its UIScrollView. It works perfectly, but if I scroll view down and stop somewhere, then switch to another viewController2, then get back to viewController1 and press tabBar icon - the viewController1 will scroll up, but Large Title will never be showed, and I should press tabBar icon one more time to show it:
The code I use for scroll up the VC1:
private var biggestTopSafeAreaInset: CGFloat = 0
override func viewSafeAreaInsetsDidChange() {
super.viewSafeAreaInsetsDidChange()
self.biggestTopSafeAreaInset = max(view.safeAreaInsets.top, biggestTopSafeAreaInset)
}
func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
if tabBarController.selectedIndex == 0 {
let navigationVC = viewController as? UINavigationController
let firstVC = navigationVC?.viewControllers.first as? CurrencyViewController
guard let scrollView = firstVC?.view.subviews.first(where: { $0 is UIScrollView }) as? UIScrollView else { return }
if traitCollection.verticalSizeClass == .compact {
scrollView.setContentOffset(CGPoint(x: 0, y: -view.safeAreaInsets.top, animated: true)
} else {
scrollView.setContentOffset(CGPoint(x: 0, y: -biggestTopSafeAreaInset, animated: true)
}
}
}
I tried to track biggestTopSafeAreaInset in different stages of VC1 life, but it always has the same number - 196.0. But then why it doesn't scroll till the Large Title after viewControllers switch?
in your tableView set contentInsetAdjustmentBehavior to never
tableView.contentInsetAdjustmentBehavior = .never
in controller update the ui of navigation bar again
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
DispatchQueue.main.async { [weak self] in
self?.navigationController?.navigationBar.sizeToFit()
}
}
here is the navigation controller
class BaseNavigationController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
if #available(iOS 15.0, *) {
let scrollAppearance = UINavigationBarAppearance()
scrollAppearance.shadowColor = .white
scrollAppearance.backgroundColor = .white
let navigationBarAppearance = UINavigationBarAppearance()
navigationBarAppearance.configureWithDefaultBackground()
navigationBarAppearance.backgroundColor = .white
navigationBarAppearance.largeTitleTextAttributes = [
NSAttributedString.Key.font: UIFont.systemFont(ofSize: 26),
NSAttributedString.Key.foregroundColor: UIColor.black
]
navigationBarAppearance.titleTextAttributes = [
NSAttributedString.Key.font: UIFont.systemFont(ofSize: 17),
NSAttributedString.Key.foregroundColor: UIColor.black
]
UINavigationBar.appearance().backIndicatorImage = UIImage(named: "back-arrow")
UINavigationBar.appearance().standardAppearance = navigationBarAppearance
UINavigationBar.appearance().compactAppearance = navigationBarAppearance
UINavigationBar.appearance().scrollEdgeAppearance = scrollAppearance
navigationBar.tintColor = .black
navigationBar.prefersLargeTitles = true
navigationBar.isTranslucent = false
navigationItem.largeTitleDisplayMode = .automatic
} else {
navigationBar.largeTitleTextAttributes = [
NSAttributedString.Key.font: UIFont.systemFont(ofSize: 26),
NSAttributedString.Key.foregroundColor: UIColor.black
]
navigationBar.titleTextAttributes = [
NSAttributedString.Key.font: UIFont.systemFont(ofSize: 17),
NSAttributedString.Key.foregroundColor: UIColor.black
]
navigationBar.tintColor = .black
navigationBar.prefersLargeTitles = true
navigationBar.isTranslucent = false
navigationItem.largeTitleDisplayMode = .automatic
navigationBar.barTintColor = .white
}
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .darkContent
}
}
here is the Tabbar Controller
class TabbarController:UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
let c1 = C1()
let c2 = C2()
let c3 = C3()
c1.tabBarItem = UITabBarItem(title: "Home", image: UIImage(named: "home786"), tag: 0)
c1.tabBarItem.tag = 0
let nav1 = BaseNavigationController(rootViewController: c1)
c2.tabBarItem = UITabBarItem(title: "Setting", image: UIImage(named: "home786"), tag: 0)
c2.tabBarItem.tag = 1
let nav2 = BaseNavigationController(rootViewController: c2)
c2.tabBarItem = UITabBarItem(title: "User", image: UIImage(named: "home786"), tag: 0)
c2.tabBarItem.tag = 2
let nav3 = BaseNavigationController(rootViewController: c3)
viewControllers = [nav1,nav2,nav3]
selectedViewController = nav1
tabBarController?.viewControllers?.first?.view.backgroundColor = .red
}
}
Try to add this in viewDidLoad:
view.addSubview(UIView())
this single line block large title navigation Bar... I don't Know why, but this trick fix momentarily the issue...
After some research I found out what can fix my problem. If you call this method with a small delay in tabBarController didSelect then it will be possible to see a Large Title after switching viewControllers. But I still can't figure out exactly why it happened...
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
navigationVC?.navigationBar.sizeToFit()
}

How to dismiss a stack of UIViewControllers to a certain Root ViewController?

Some RootViewController presents a ParentViewController which than presents a ChildViewController.
How can I dissmiss the ChildViewController animated directly to the RootViewController whithout showing the ParentViewController again?
In Detail
Assume some presents the ParentViewController which lets the user enter some credentials to login to some user account.
Once the connection is established the ParentViewController presents the ChildViewController which shows connection / account details to the user
When the user closes the ChildViewController it should be dismissed animated (slide down, etc.). But instead of returning to the ParentViewController the user should get back directly to the RootViewController
Of course it would be possible, that the ParentViewController does not present the ChildViewController itself but (somehow) tells the RootViewController to this. This way it would be no problem to directly return from the ChildViewController to the RootViewController. However, this is NOT what I am looking for, since the RootViewController should not know about the ChildViewController or even care if the ParentViewController presents other VCs.
I am looking for a solution where the ParentViewController controls whether itself is shown after the VC it presented is dismissed or its parent (= the root VC).
Code:
typealias CompletionBlock = () -> Void
class RootViewController: UIViewController {
#IBAction func showParentVC(_ sender: Any) {
let parentVC = ParentViewController()
parentVC.completion = {
self.dismiss(animated: true, completion: nil)
}
present(parentVC, animated: true)
}
}
class ParentViewController: UIViewController {
var completion: CompletionBlock?
#IBAction func showChild(_ sender: Any) {
let childVC = ChildViewController()
childVC.completion = {
self.completion?()
}
present(childVC, animated: true)
}
}
class ChildViewController: UIViewController {
var completion: CompletionBlock?
#IBAction func close(_ sender: Any) {
completion?()
}
}
Using this code does NOT solve the described problem. If close is called on the ChildViewController the RootViewController calls self.dismiss(animated: true, completion: nil). This way the ChildViewController animates away and the ParentViewController becomes visible. Then the ParentViewController animates away and the RootViewControllerbecomes visible.
How to skip the ParentViewController and directly show the RootViewController after animating away the ChildViewController?
My recommendation is embed your RootViewController into a NavigationController (if you don't have it yet) and present both parent a child with
navigationController?.present(viewController, animated: true, completion: nil)
//instead of viewController.present(...)
And then youcan use this method from your childViewController
navigationController?.popToRootViewController(animated: true)
One approach would be to set the view's alpha to Zero when you present another VC onto the "stack" of presented VCs.
So, present the first modal VC from the "root" VC as normal. For each "child" that presents another VC, use:
present(vc, animated: true, completion: {
self.view.alpha = 0.0
})
Now, when you call-back to the "root" VC to dismiss all the VCs, you won't see the partial / flash of the intermediate VC / VCs.
Here is a complete example to test. No #IBOutlets or #IBActions ... just start with a black view controller and assign its Custom Class to MultiPresentDismissViewController:
import UIKit
class MultiPresentDismissViewController: UIViewController {
let theLabel: UILabel = {
let v = UILabel()
v.textAlignment = .center
v.font = UIFont.boldSystemFont(ofSize: 40)
v.backgroundColor = .yellow
v.text = "\"Root\" VC"
return v
}()
let showAnotherButton: UIButton = {
let v = UIButton()
v.backgroundColor = UIColor(white: 0.9, alpha: 1.0)
v.setTitle("Present a VC", for: .normal)
v.setTitleColor(.blue, for: .normal)
v.setTitleColor(.cyan, for: .highlighted)
return v
}()
let theStackView: UIStackView = {
let v = UIStackView()
v.axis = .vertical
v.alignment = .fill
v.distribution = .fill
v.spacing = 32
return v
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
[theLabel, showAnotherButton].forEach {
theStackView.addArrangedSubview($0)
$0.layer.borderWidth = 1.0
}
theStackView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(theStackView)
NSLayoutConstraint.activate([
theStackView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
theStackView.topAnchor.constraint(equalTo: view.topAnchor, constant: 100.0),
theStackView.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.8),
])
showAnotherButton.addTarget(self, action: #selector(presentAnotherVC), for: .touchUpInside)
}
#objc func presentAnotherVC() -> Void {
let vc = AnotherViewController()
vc.myID = 1
present(vc, animated: true, completion: nil)
}
}
class AnotherViewController: UIViewController {
let theLabel: UILabel = {
let v = UILabel()
v.textAlignment = .center
v.font = UIFont.boldSystemFont(ofSize: 100)
v.backgroundColor = .yellow
return v
}()
let showAnotherButton: UIButton = {
let v = UIButton()
v.backgroundColor = UIColor(white: 0.9, alpha: 1.0)
v.setTitle("Present Another VC", for: .normal)
v.setTitleColor(.blue, for: .normal)
v.setTitleColor(.cyan, for: .highlighted)
return v
}()
let defaultDismissButton: UIButton = {
let v = UIButton()
v.backgroundColor = UIColor(white: 0.9, alpha: 1.0)
v.setTitle("Default Dismiss All", for: .normal)
v.setTitleColor(.blue, for: .normal)
v.setTitleColor(.cyan, for: .highlighted)
return v
}()
let theStackView: UIStackView = {
let v = UIStackView()
v.axis = .vertical
v.alignment = .fill
v.distribution = .fill
v.spacing = 20
return v
}()
var myID: Int = 0
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .random()
[theLabel, showAnotherButton, defaultDismissButton].forEach {
theStackView.addArrangedSubview($0)
$0.layer.borderWidth = 1.0
}
theStackView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(theStackView)
NSLayoutConstraint.activate([
theStackView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
theStackView.topAnchor.constraint(equalTo: view.topAnchor, constant: 100.0),
theStackView.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.8),
])
theLabel.text = "\(myID)"
showAnotherButton.addTarget(self, action: #selector(presentAnotherVC), for: .touchUpInside)
defaultDismissButton.addTarget(self, action: #selector(defaultDismissAll), for: .touchUpInside)
}
#objc func presentAnotherVC() -> Void {
let vc = AnotherViewController()
vc.myID = myID + 1
present(vc, animated: true, completion: {
self.view.alpha = 0.0
})
}
#objc func defaultDismissAll() -> Void {
// walk up the "presenting" hierarchy to find the "root" VC
var vc = self.presentingViewController
while vc?.presentingViewController != nil {
vc = vc?.presentingViewController
}
vc?.dismiss(animated: true, completion: nil)
}
}
extension CGFloat {
static func random() -> CGFloat {
return CGFloat(arc4random()) / CGFloat(UInt32.max)
}
}
extension UIColor {
static func random() -> UIColor {
return UIColor(red: .random(),
green: .random(),
blue: .random(),
alpha: 1.0)
}
}

How to add a segmented control to a navigation bar ? (iOS)

I would like to add a segmented control to a navigation bar like this
but when i drag the segmented control to the navigation bar the large title is gone. How can create the above UI ?
You should add the segmented control as the titleView of the navigation bar.
Below is the sample code:
let titles = ["All", "Missed"]
segmentControl = UISegmentedControl(items: titles)
segmentControl.tintColor = UIColor.white
segmentControl.backgroundColor = UIColor.blue
segmentControl.selectedSegmentIndex = 0
for index in 0...titles.count-1 {
segmentControl.setWidth(120, forSegmentAt: index)
}
segmentControl.sizeToFit()
segmentControl.addTarget(self, action: #selector(segmentChanged), for: .valueChanged)
segmentControl.selectedSegmentIndex = 0
segmentControl.sendActions(for: .valueChanged)
navigationItem.titleView = segmentControl
You can try the below simple code,
var segmentedController: UISegmentedControl!
let items = ["Label A", "Label B"]
segmentedController = UISegmentedControl(items: items)
navigationItem.titleView = segmentedController
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Edit", style: .plain, target: self, action: #selector(handleSignOut))
navigationItem.rightBarButtonItem?.tintColor = UIColor.black
If you want to add UISegmentControl by using XIB then you can do that by following these simple steps:
Design your custom view in XIB (Refer XIB for your reference https://i.stack.imgur.com/AJDCo.png)
Put the code in your ViewController
class ViewController: UIViewController {
lazy var navSegmentedView: YourCustomView = {
guard let aView = Bundle.main.loadNibNamed("\(YourCustomView.self)", owner: self, options: nil)?.first as? YourCustomView else { return YourCustomView() }
aView.backgroundColor = .clear
aView.frame = CGRect(x: 0, y: 0, width: 160, height: 40)
aView.segmentControl.addTarget(self, action: #selector(segmentChanged(_:)), for: .valueChanged)
return aView
}()
override func viewDidLoad() {
super.viewDidLoad()
setupNavBar()
}
func setupNavBar() {
navigationItem.titleView = navSegmentedView
navigationItem.titleView?.backgroundColor = .clear
}
#objc func segmentChanged(_ sender: UISegmentedControl) {
print(sender.selectedSegmentIndex)
}
}

NavigationItem titleView is coming at left side for some time then move to Center

I am setting a custom view as titleView of the navigation. When viewcontroller appear its title view comes at left side for a moment and then move to center,what could be wrong? I am using the following code
let itemImgs: [UIImage] = [UIImage(named: "MORE_Location")!, UIImage(named: "MORE_Department")!, UIImage(named: "By_Teams")!, UIImage(named: "MORE_Status")!]
self.navigationController?.navigationBar.isTranslucent = false
self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white]
menuView = BTNavigationDropdownMenu(navigationController: self.navigationController, containerView: self.navigationController!.view, title: AppMessage.EDEmployeePeople, items: items as [AnyObject], itemImgs: itemImgs)
menuView.cellHeight = 60
menuView.cellBackgroundColor = UIColor.red
menuView.cellSelectionColor = UIColor.clear
menuView.cellSeparatorColor = UIColor.clear
menuView.shouldKeepSelectedCellColor = false
menuView.cellTextLabelColor = UIColor.white
menuView.shouldChangeTitleText = false
menuView.cellTextLabelFont = UIFont(name: "Helvetica", size: 17)
if appNeedsAutoResize
{
menuView.cellTextLabelFont = UIUtils.getFontForApproprieteField(.subHeadline).font
}
menuView.cellTextLabelAlignment = .left // .Center // .Right // .Left
menuView.arrowPadding = 15
menuView.animationDuration = 0.5
menuView.maskBackgroundColor = UIColor.clear
menuView.maskBackgroundOpacity = 0.3
menuView.didSelectItemAtIndexHandler = {(indexPath: Int) -> () in
print("Did select item at index: \(indexPath)")
if indexPath == 3
{
let byStatusViewController = ByStatusViewController(nibName: "ByStatusViewController", bundle: nil)
//UIUtils.pushViewWhenHideBottom(self, anotherVC: byStatusViewController)
self.navigationController?.pushViewController(byStatusViewController, animated: true)
}
else
{
let dropVC = DepartmentViewController(nibName: "DepartmentViewController", bundle: nil)
switch indexPath
{
case 0:
dropVC.employeeGroupInfo = EmployeeGroupInfo.locationInfo
break
case 1:
dropVC.employeeGroupInfo = EmployeeGroupInfo.departmentInfo
break
default:
dropVC.employeeGroupInfo = EmployeeGroupInfo.teamInfo
break
}
// UIUtils.pushViewWhenHideBottom(self, anotherVC: dropVC)
self.navigationController?.pushViewController(dropVC, animated: true)
}
}
self.navigationItem.titleView = menuView
}
Try to add constraints of autoresizing masks to your menu view to keep the view centered.
E.g.
menuView.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin, .flexibleBottomMargin]
I had this problem and changing my function that customize my navigationItem from viewWillAppear() to viewDidLoad() resolved

Make custom button on Tab Bar rounded

Here is what I am trying to do:
Note: The screenshot is taken from an earlier version of iOS
What I have been able to achieve:
Code:
override func viewWillAppear(animated: Bool) {
// Creates image of the Button
let imageCameraButton: UIImage! = UIImage(named: "cameraIcon")
// Creates a Button
let cameraButton = UIButton(type: .Custom)
// Sets width and height to the Button
cameraButton.frame = CGRectMake(0.0, 0.0, imageCameraButton.size.width, imageCameraButton.size.height);
// Sets image to the Button
cameraButton.setBackgroundImage(imageCameraButton, forState: .Normal)
// Sets the center of the Button to the center of the TabBar
cameraButton.center = self.tabBar.center
// Sets an action to the Button
cameraButton.addTarget(self, action: "doSomething", forControlEvents: .TouchUpInside)
// Adds the Button to the view
self.view.addSubview(cameraButton)
}
I did try to create a rounded button in the normal way, but this was the result:
Code Snippet for rounded button:
//Creation of Ronded Button
cameraButton.layer.cornerRadius = cameraButton.frame.size.width/2
cameraButton.clipsToBounds = true
Solution
You need to subclass UITabBarController and then add the button above TabBar's view. A button action should trigger UITabBarController tab change by setting selectedIndex.
Code
The code below only is a simple approach, however for a full supporting iPhone (including X-Series)/iPad version you can check the full repository here: EBRoundedTabBarController
class CustomTabBarController: UITabBarController {
// MARK: - View lifecycle
override func viewDidLoad() {
super.viewDidLoad()
let controller1 = UIViewController()
controller1.tabBarItem = UITabBarItem(tabBarSystemItem: .contacts, tag: 1)
let nav1 = UINavigationController(rootViewController: controller1)
let controller2 = UIViewController()
controller2.tabBarItem = UITabBarItem(tabBarSystemItem: .contacts, tag: 2)
let nav2 = UINavigationController(rootViewController: controller2)
let controller3 = UIViewController()
let nav3 = UINavigationController(rootViewController: controller3)
nav3.title = ""
let controller4 = UIViewController()
controller4.tabBarItem = UITabBarItem(tabBarSystemItem: .contacts, tag: 4)
let nav4 = UINavigationController(rootViewController: controller4)
let controller5 = UIViewController()
controller5.tabBarItem = UITabBarItem(tabBarSystemItem: .contacts, tag: 5)
let nav5 = UINavigationController(rootViewController: controller5)
viewControllers = [nav1, nav2, nav3, nav4, nav5]
setupMiddleButton()
}
// MARK: - Setups
func setupMiddleButton() {
let menuButton = UIButton(frame: CGRect(x: 0, y: 0, width: 64, height: 64))
var menuButtonFrame = menuButton.frame
menuButtonFrame.origin.y = view.bounds.height - menuButtonFrame.height
menuButtonFrame.origin.x = view.bounds.width/2 - menuButtonFrame.size.width/2
menuButton.frame = menuButtonFrame
menuButton.backgroundColor = UIColor.red
menuButton.layer.cornerRadius = menuButtonFrame.height/2
view.addSubview(menuButton)
menuButton.setImage(UIImage(named: "example"), for: .normal)
menuButton.addTarget(self, action: #selector(menuButtonAction(sender:)), for: .touchUpInside)
view.layoutIfNeeded()
}
// MARK: - Actions
#objc private func menuButtonAction(sender: UIButton) {
selectedIndex = 2
}
}
Output
Swift 3 Solution
With a slight adjustment to EricB's solution to have this work for Swift 3, the menuButton.addTarget() method needs to have it's selector syntax changed a bit.
Here is the new menuButton.addTarget() function:
menuButton.addTarget(self, action: #selector(MyTabBarController.menuButtonAction), for: UIControlEvents.touchUpInside)
When defining my TabBarController class, I also add a UITabBarControllerDelegate and placed all of the that in the
override func viewDidAppear(_ animated: Bool) { ... }
For extra clarity, the full code is:
Full Code Solution
import UIKit
class MyTabBarController: UITabBarController, UITabBarControllerDelegate {
// View Did Load
override func viewDidLoad() {
super.viewDidLoad()
}
// Tab Bar Specific Code
override func viewDidAppear(_ animated: Bool) {
let controller1 = UIViewController(self.view.backgroundColor = UIColor.white)
controller1.tabBarItem = UITabBarItem(tabBarSystemItem: UITabBarSystemItem.contacts, tag: 1)
let nav1 = UINavigationController(rootViewController: controller1)
let controller2 = UIViewController()
controller2.tabBarItem = UITabBarItem(tabBarSystemItem: UITabBarSystemItem.contacts, tag: 2)
let nav2 = UINavigationController(rootViewController: controller2)
let controller3 = UIViewController()
let nav3 = UINavigationController(rootViewController: controller3)
nav3.title = ""
let controller4 = UIViewController()
controller4.tabBarItem = UITabBarItem(tabBarSystemItem: UITabBarSystemItem.contacts, tag: 4)
let nav4 = UINavigationController(rootViewController: controller4)
let controller5 = UIViewController()
controller5.tabBarItem = UITabBarItem(tabBarSystemItem: UITabBarSystemItem.contacts, tag: 5)
let nav5 = UINavigationController(rootViewController: controller5)
self.viewControllers = [nav1, nav2, nav3, nav4, nav5]
self.setupMiddleButton()
}
// TabBarButton – Setup Middle Button
func setupMiddleButton() {
let menuButton = UIButton(frame: CGRect(x: 0, y: 0, width: 64, height: 64))
var menuButtonFrame = menuButton.frame
menuButtonFrame.origin.y = self.view.bounds.height - menuButtonFrame.height
menuButtonFrame.origin.x = self.view.bounds.width / 2 - menuButtonFrame.size.width / 2
menuButton.frame = menuButtonFrame
menuButton.backgroundColor = UIColor.red
menuButton.layer.cornerRadius = menuButtonFrame.height/2
self.view.addSubview(menuButton)
menuButton.setImage(UIImage(named: "example"), for: UIControlState.normal)
menuButton.addTarget(self, action: #selector(MyTabBarController.menuButtonAction), for: UIControlEvents.touchUpInside)
self.view.layoutIfNeeded()
}
// Menu Button Touch Action
func menuButtonAction(sender: UIButton) {
self.selectedIndex = 2
// console print to verify the button works
print("Middle Button was just pressed!")
}
}
This is the customTabbarcontroller class which is the subclass of UITabbarcontroller. It's the same idea as given by #EridB. But in his code #Raymond26's issue wasn't solved. So, posting a complete solution written in Swift 3.0
protocol CustomTabBarControllerDelegate
{
func customTabBarControllerDelegate_CenterButtonTapped(tabBarController:CustomTabBarController, button:UIButton, buttonState:Bool);
}
class CustomTabBarController: UITabBarController, UITabBarControllerDelegate
{
var customTabBarControllerDelegate:CustomTabBarControllerDelegate?;
var centerButton:UIButton!;
private var centerButtonTappedOnce:Bool = false;
override func viewDidLayoutSubviews()
{
super.viewDidLayoutSubviews();
self.bringcenterButtonToFront();
}
override func viewDidLoad()
{
super.viewDidLoad()
self.delegate = self;
self.tabBar.barTintColor = UIColor.red;
let dashboardVC = DashboardViewController()
dashboardVC.tabBarItem = UITabBarItem(tabBarSystemItem: .topRated, tag: 1)
let nav1 = UINavigationController(rootViewController: dashboardVC)
let myFriendsVC = MyFriendsViewController()
myFriendsVC.tabBarItem = UITabBarItem(tabBarSystemItem: .featured, tag: 2)
let nav2 = UINavigationController(rootViewController: myFriendsVC)
let controller3 = UIViewController()
let nav3 = UINavigationController(rootViewController: controller3)
nav3.title = ""
let locatorsVC = LocatorsViewController()
locatorsVC.tabBarItem = UITabBarItem(tabBarSystemItem: .downloads, tag: 4)
let nav4 = UINavigationController(rootViewController: locatorsVC)
let getDirectionsVC = GetDirectionsViewController()
getDirectionsVC.tabBarItem = UITabBarItem(tabBarSystemItem: .history, tag: 5)
let nav5 = UINavigationController(rootViewController: getDirectionsVC)
viewControllers = [nav1, nav2, nav3, nav4, nav5]
self.setupMiddleButton()
}
// MARK: - TabbarDelegate Methods
func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController)
{
switch viewController
{
case is DashboardViewController:
self.showCenterButton()
case is MyFriendsViewController:
self.showCenterButton()
case is GetDirectionsViewController:
self.showCenterButton()
case is LocatorsViewController:
self.showCenterButton()
default:
self.showCenterButton()
}
}
// MARK: - Internal Methods
#objc private func centerButtonAction(sender: UIButton)
{
// selectedIndex = 2
if(!centerButtonTappedOnce)
{
centerButtonTappedOnce=true;
centerButton.setImage(UIImage(named: "ic_bullseye_white"), for: .normal)
}
else
{
centerButtonTappedOnce=false;
centerButton.setImage(UIImage(named: "ic_bullseye_red"), for: .normal)
}
customTabBarControllerDelegate?.customTabBarControllerDelegate_CenterButtonTapped(tabBarController: self,
button: centerButton,
buttonState: centerButtonTappedOnce);
}
func hideCenterButton()
{
centerButton.isHidden = true;
}
func showCenterButton()
{
centerButton.isHidden = false;
self.bringcenterButtonToFront();
}
// MARK: - Private methods
private func setupMiddleButton()
{
centerButton = UIButton(frame: CGRect(x: 0, y: 0, width: 64, height: 64))
var centerButtonFrame = centerButton.frame
centerButtonFrame.origin.y = view.bounds.height - centerButtonFrame.height
centerButtonFrame.origin.x = view.bounds.width/2 - centerButtonFrame.size.width/2
centerButton.frame = centerButtonFrame
centerButton.backgroundColor = UIColor.red
centerButton.layer.cornerRadius = centerButtonFrame.height/2
view.addSubview(centerButton)
centerButton.setImage(UIImage(named: "ic_bullseye_red"), for: .normal)
centerButton.setImage(UIImage(named: "ic_bullseye_white"), for: .highlighted)
centerButton.addTarget(self, action: #selector(centerButtonAction(sender:)), for: .touchUpInside)
view.layoutIfNeeded()
}
private func bringcenterButtonToFront()
{
print("bringcenterButtonToFront called...")
self.view.bringSubview(toFront: self.centerButton);
}
}
This is the DashboardViewController for complete reference:
class DashboardViewController: BaseViewController, CustomTabBarControllerDelegate
{
override func viewDidLoad()
{
super.viewDidLoad()
(self.tabBarController as! CustomTabBarController).customTabBarControllerDelegate = self;
}
override func viewWillAppear(_ animated: Bool)
{
super.viewWillAppear(animated);
(self.tabBarController as! CustomTabBarController).showCenterButton();
}
override func viewWillDisappear(_ animated: Bool)
{
super.viewWillDisappear(animated);
self.hidesBottomBarWhenPushed = false;
(self.tabBarController as! CustomTabBarController).hideCenterButton();
}
override func viewWillLayoutSubviews()
{
super.viewWillLayoutSubviews();
if(!isUISetUpDone)
{
self.view.backgroundColor = UIColor.lightGray
self.title = "DASHBOARD"
self.prepareAndAddViews();
self.isUISetUpDone = true;
}
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
//MARK: CustomTabBarControllerDelegate Methods
func customTabBarControllerDelegate_CenterButtonTapped(tabBarController: CustomTabBarController, button: UIButton, buttonState: Bool)
{
print("isDrive ON : \(buttonState)");
}
//MARK: Internal Methods
func menuButtonTapped()
{
let myFriendsVC = MyFriendsViewController()
myFriendsVC.hidesBottomBarWhenPushed = true;
self.navigationController!.pushViewController(myFriendsVC, animated: true);
}
//MARK: Private Methods
private func prepareAndAddViews()
{
let menuButton = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50))
menuButton.titleLabel?.text = "Push"
menuButton.titleLabel?.textColor = UIColor.white
menuButton.backgroundColor = UIColor.red;
menuButton.addTarget(self, action: #selector(DashboardViewController.menuButtonTapped), for: .touchUpInside)
self.view.addSubview(menuButton);
}
}
with StoryBoard:
Click the tab bar button within the view controller of the particular tab bar item you want to make prominent,
Remove the text, just set the image inset top to -25 of the tab bar button.
Check Like Below image

Resources