Void { self.navigati-6ren">
gpt4 book ai didi

ios - 如何以编程方式在 Swift 中创建 "Back"UIBarButton 项目?

转载 作者:IT王子 更新时间:2023-10-29 05:24:41 26 4
gpt4 key购买 nike

我能够创建一个可以使用以下代码以编程方式返回的 UIBarButton 项目:

    func backAction() -> Void {        
self.navigationController?.popViewControllerAnimated(true)
}
override func viewDidLoad() {
super.viewDidLoad()
let backButton = UIBarButtonItem(title: "Back", style: UIBarButtonItemStyle.Plain, target: self, action: "backAction")

self.navigationItem.leftBarButtonItem = backButton
}

问题是后退按钮没有左箭头: enter image description here有没有办法让它看起来像一个带有箭头的常规后退按钮,如下所示:enter image description here

我还想知道是否有办法将按钮标题名称设为前一个 View Controller 的标题,如果可能的话。

谢谢

最佳答案

下面是使用带有图像的 UIButton 的代码,您可以将其添加为 UIBarButtonItem 的自定义 View

override func viewDidLoad() {
super.viewDidLoad()
var backbutton = UIButton(type: .Custom)
backbutton.setImage(UIImage(named: "BackButton.png"), forState: .Normal) // Image can be downloaded from here below link
backbutton.setTitle("Back", forState: .Normal)
backbutton.setTitleColor(backbutton.tintColor, forState: .Normal) // You can change the TitleColor
backbutton.addTarget(self, action: "backAction", forControlEvents: .TouchUpInside)

self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: backbutton)
}

func backAction() -> Void {
self.navigationController?.popViewControllerAnimated(true)
}

BackButton.png Download Link

要使用之前的 View Controller 标题设置后退按钮的标题,您必须在呈现 Controller 时将标题作为字符串传递,将上述代码更改为

var titleStrFromPreviousController: String // This value has to be set from previous controller while presenting modal controller
backbutton.setTitle(titleStrFromPreviousController, forState: .Normal)

这可能会有所帮助。

swift 3

override func viewDidLoad() {
super.viewDidLoad()

addBackButton()
}

func addBackButton() {
let backButton = UIButton(type: .custom)
backButton.setImage(UIImage(named: "BackButton.png"), for: .normal) // Image can be downloaded from here below link
backButton.setTitle("Back", for: .normal)
backButton.setTitleColor(backButton.tintColor, for: .normal) // You can change the TitleColor
backButton.addTarget(self, action: #selector(self.backAction(_:)), for: .touchUpInside)

self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: backButton)
}

@IBAction func backAction(_ sender: UIButton) {
let _ = self.navigationController?.popViewController(animated: true)
}

关于ios - 如何以编程方式在 Swift 中创建 "Back"UIBarButton 项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34279332/

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