简体   繁体   中英

Navigate to viewcontroller from a subclass function in swift

I've created a UINavigationController with a UIToolbar . Inside the UIToolbar there are multiple UIBarButtonItems . The UIToolbar has a subclass which i use to set the toolbar settings and create the UIBarButtonItems .

By pressing a UIBarButtonItem I want to navigate to another ViewController. As you can see in the code below, I've created a function for .addTarget , called " settingsPressed ".

//SetToolbar

class ToolbarClass: UIToolbar {

//Set height of toolbar
override func sizeThatFits(_ size: CGSize) -> CGSize {
    var size = super.sizeThatFits(size)
    size.height = 60
    return size
}

//Toolbar settings
override func layoutSubviews() {
    super.layoutSubviews()

    //Default
    self.isTranslucent = false
    self.barTintColor = UIColor(red: 48/255, green: 148/255, blue: 172/255, alpha: 1)

    //Buttons

    //Settings
    let settingsBtn = UIButton()
    settingsBtn.frame = CGRect(x: 0, y: 0, width: 46, height: 46)
    settingsBtn.setImage(UIImage(named: "Settings-Button")?.withRenderingMode(.alwaysOriginal), for: .normal)
    settingsBtn.addTarget(self, action: #selector(self.settingsPressed), for: .touchUpInside)
    let settingsButton = UIBarButtonItem()
    settingsButton.customView = settingsBtn


    self.setItems([settingsButton], animated: false)

}

func settingsPressed() {
   //How to navigate to a viewcontroller?
}

}

I've found some swift codes to navigate to another viewcontroller, but these codes don't work in my situation because i'm using a subclass. In this case the ".self.storyboard?" doesn't make sense:

let secondViewController = self.storyboard?.instantiateViewController(withIdentifier: "ClassesOverviewViewController") as!  ClassesOverviewViewController
self.navigationController?.pushViewController(secondViewController, animated: true)

Your implementation breaks MVC principles and causes the problems which you shouldn't face at all. You should not add controller logic (creating new VC and navigating to it) into view (UIToolbar and it's subclass are view elements).

  1. First way to fix it: add UIToolbar to storyboard view with added settings bar button item, connect action of bar button item with function from your VC, implement this function to navigate.
  2. Second way to fix it: leave subclass of UIToolbar (it is not preferable if you only adding bar button item in subclass), declare public property for settings bar button item, use target and action to set your VC as target and function from VC as action for settings bar button item, implement this function to navigate.

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