簡単な方法は、UIViewController
から派生したBaseViewController
という1つのプロジェクトを作成することです。すべてのviewControllerにcustom leftBarButton
を作成するには、BaseViewController
の共通メソッドを使用できます。プロジェクトの残りの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もう少し詳しく教えてもらえますか?ご協力ありがとうございました。 –