我能够创建一个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 }
问题是后退按钮没有左箭头: 有没有办法让它看起来像一个带箭头的常规后退按钮,如下所示:
我还想知道是否有办法将按钮标题名称作为前一个视图控制器的标题,如果可能的话.
谢谢
下面是使用UIButton和图像的代码,您可以将其添加为UIBarButtonItem的customView
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) }
下载链接
要使用前一个视图控制器标题设置后退按钮的标题,您必须将标题作为字符串传递,同时显示控制器,将上述代码更改为
var titleStrFromPreviousController: String // This value has to be set from previous controller while presenting modal controller backbutton.setTitle(titleStrFromPreviousController, forState: .Normal)
这可能有所帮助.
斯威夫特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) }
已为Swift 4.2更新 -感谢Sam Bing和Silentbeep
对某些颜色和动作的选择器进行了一些修改。
override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = .blue self.navigationItem.title = title self.navigationController?.navigationBar.barTintColor = .white self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: makeBackButton()) } func makeBackButton() -> UIButton { let backButtonImage = UIImage(named: "backbutton")?.withRenderingMode(.alwaysTemplate) let backButton = UIButton(type: .custom) backButton.setImage(backButtonImage, for: .normal) backButton.tintColor = .blue backButton.setTitle(" Back", for: .normal) backButton.setTitleColor(.blue, for: .normal) backButton.addTarget(self, action: #selector(self.backButtonPressed), for: .touchUpInside) return backButton } @objc func backButtonPressed() { dismiss(animated: true, completion: nil) // navigationController?.popViewController(animated: true) }