我使用UINavigationController
创建了UIToolbar
。在UIToolbar
内,有多个UIBarButtonItems
。 UIToolbar
有一个子类,我用它来设置工具栏设置并创建UIBarButtonItems
。
按UIBarButtonItem
我要导航到另一个ViewController。正如您在下面的代码中看到的,我为.addTarget
创建了一个名为“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?
}
}
我发现了一些快速代码导航到另一个viewcontroller,但这些代码在我的情况下不起作用,因为我正在使用子类。在这种情况下,“。self.storyboard?”没有意义:
let secondViewController = self.storyboard?.instantiateViewController(withIdentifier: "ClassesOverviewViewController") as! ClassesOverviewViewController
self.navigationController?.pushViewController(secondViewController, animated: true)