简体   繁体   中英

Swift custom toolbar implementation

I'm trying to implement a custom UIToolbar. The toolbar currently has 5 buttons: 3 change the content on the page (keeping the same toolbar with toggled item selected) & the other two segue to modal view controllers.

How to segment the code/views amongst the several different "pages"?

I currently have a class called ToolbarViewController that instantiates the toolbar with the different items. It has a generic action that switches the button titles "ON" and performs different actions depending on which one was tapped. Each subsequent VC that needs to have that toolbar just subclasses ToolbarViewController and the toolbar is automatically created without code replication.

By segueing this way, if the user is in tab1 and presses button1 the program crashes, because there's no segue from tab1 to tab1. One way I have been able to fix this is by having an initializer in ToolbarViewController that receives the "currentTab" and doesn't allow segues for that tab. This seems incredibly inefficient.

Another solution I've been considering is having a single VC that has the toolbar. By pressing a button, I would be able to change the View of that VC. This also has a problem, I can't have AutoLayout set in storyboard, because the VC doesn't segue to anything, just changes the view itself. This will become a problem when I need some complex views with constraints everywhere.

Are any of the 2 approaches I listed advisable? If not, what approach should I take & how should I implement these changes?

I think you should use a TabBar instead of a toolbar as you can achieve much of the same functionality I believe you are trying to achieve with greater ease.

However if you are determined to preserve the modal segues you can setup actions for each of your toolbar button presses. Give your toolbar buttons action properties.

In Swift:

UIBarButtonItem(title: "YourTitle", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(YourVC.yourMethod(_:)))

func yourMethod() {
   (code here)
}

As far as your problem with AutoLayout, you should drop an empty view into your ToolBarViewController then create custom UIView subclasses with nibs. Setup the way you want each view to look in the nibs with your constraints. Then, in code, load each custom UIView Subclass into the empty view on your ToolBarViewController.

Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM