gpt4 book ai didi

ios - 在我的应用程序中创建自定义后退按钮

转载 作者:行者123 更新时间:2023-11-28 15:23:52 25 4
gpt4 key购买 nike

我正在尝试更改整个应用中导航 Controller 后退按钮的默认外观。

我想使用 and image(icon) 并删除“返回”文本。此代码将图像拉伸(stretch)到按钮上,但不会删除按钮标题。

let backImg: UIImage = UIImage(named: "icon_back")!
UIBarButtonItem.appearance().setBackButtonBackgroundImage(backImg, for: .normal, barMetrics: .default)

在 AppDelegate (didFinishLaunchingWithOptions) 中建议如何做?

最佳答案

最简单的方法就是为您的项目创建一个 BaseViewController,它派生自 UIViewController。您可以使用 BaseViewController 中的常用方法在每个 viewController 中创建您的自定义 leftBarButton。项目中剩余的 viewController 应该是派生自这个 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
}

}

谢谢。

关于ios - 在我的应用程序中创建自定义后退按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45558188/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com