简单的做法是为您的项目创建一个BaseViewController
,该项目源自UIViewController
。您可以使用BaseViewController
中的常用方法在每个viewController中创建custom leftBarButton
。在项目中剩余的viewController应derived from this BaseViewController
,
class BaseViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
createLeftBarButton(image: #Pass image here#, width: #Pass width of your image view#) // Create custom back bar button.
}
/**Create cutom back bar button*/
func createLeftBarButton(image: UIImage?, width: CGFloat) {
let backButton: UIButton = UIButton(frame: CGRect(x: 0, y: 0, width: width, height: 50))
backButton.imageView?.contentMode = .scaleAspectFill
backButton.imageView?.bounds = CGRect(x: 0, y: 0, width: width, height: width)
backButton.setImage(image, for: .normal)
backButton.setImage(image, for: .highlighted)
backButton.addTarget(self, action: #selector(leftBarButtonItemPressed(_:)), for: .touchUpInside)
let leftItem: UIBarButtonItem = UIBarButtonItem(customView: backButton)
navigationItem.leftBarButtonItem = leftItem
}
/**Custom back bar button pressed. So handle here*/
func leftBarButtonItemPressed(_ sender: UIButton) {
view.endEditing(true) // End editing if any.
if isViewControllerPresented() { // Check view controller is presented or pushed
dismiss(animated: true, completion: nil) // Dismiss ViewController if presented
} else {
_ = navigationController?.popViewController(animated: true) // Pop ViewController if pushed
}
}
/**To check whether view controller is presented or pushed.*/
func isViewControllerPresented() -> Bool {
if self.presentingViewController?.presentedViewController == self {
return true
}
if (self.navigationController != nil && self.navigationController?.presentingViewController?.presentedViewController == self.navigationController) && self.navigationController?.viewControllers.count == 1 {
return true
}
if self.tabBarController?.presentingViewController is UITabBarController {
return true
}
return false
}
}
// Sub class your remaining viewControllers like this.
class FirstViewController: BaseViewController {
override func viewDidLoad() {
super.viewDidLoad() // When calling this super method, the custom back bar button will be created for you
}
}
感谢。
用它创建UIViewController的基类子类。 –
@ElTomato你能解释一下吗?感谢您的帮助。 –