斯威夫特:设置"返回"默认按钮文本为" segue back"按键

时间:2017-12-02 13:54:24

标签: ios swift localization

我正在寻找一种方法来将所有后退按钮文本设置为"返回"而不是默认情况下显示segue来自的视图的标题。

我有多个视图和segues,希望有一种比在所有视图控制器中使用PrepareForSegue更简洁的方法。

这样可以简化本地化,因为我让用户能够更改语言。

有人有任何建议或解决方案吗?

2 个答案:

答案 0 :(得分:1)

为UIViewController创建扩展(您可以为此创建不同的空文件,并确保导入UIKIt) - :

import UIKit
extension UIViewController  {


    func leftBarButton(subView:UIView,labelView:UILabel,imageView:UIImageView) -> UIBarButtonItem{

        let leftBarButton = UIBarButtonItem(customView: subView)
        subView.frame = CGRect(x: 0, y: 0, width: 100, height: 40)
        subView.addSubview(imageView)
        subView.addSubview(labelView)

        imageView.leftAnchor.constraint(equalTo: subView.leftAnchor,constant: -8).isActive = true
        imageView.topAnchor.constraint(equalTo: subView.topAnchor, constant: 2).isActive = true
        imageView.heightAnchor.constraint(equalToConstant: 30).isActive = true
        imageView.widthAnchor.constraint(equalToConstant: 30).isActive = true

        labelView.leftAnchor.constraint(equalTo: imageView.rightAnchor,constant: 8).isActive  = true
        labelView.rightAnchor.constraint(equalTo: subView.rightAnchor).isActive = true
        labelView.topAnchor.constraint(equalTo: subView.topAnchor).isActive = true
        labelView.heightAnchor.constraint(equalToConstant: 40).isActive = true

        return leftBarButton
    }

    func anotherMethod(){
       _ =  self.navigationController?.popViewController(animated: true)
    }
}

在控制器类中:

  var views : UIView = {
        let subView = UIView()
        //subView.backgroundColor = UIColor.green
        return subView
    }()

    var imageView : UIImageView = {
        var view = UIImageView()
        view.translatesAutoresizingMaskIntoConstraints = false
        view.image = UIImage(named: "Back")
        return view
    }()

    var labelView: UILabel = {
        var labeView = UILabel()
        labeView.translatesAutoresizingMaskIntoConstraints = false
        labeView.text = "Back"
        labeView.textColor = UIColor.blue
        return labeView
    }()

    // ViewDidLoad
    override func viewDidLoad() {
        super.viewDidLoad()
        //self.navigationBar.tintColor = UIColor.green
       self.navigationItem.leftBarButtonItem = leftBarButton(subView: views, labelView: labelView, imageView: imageView)


    }

答案 1 :(得分:0)

由于没有你需要的外观代理,你可以继承路由并创建一个这样的基类:

class BaseClass: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        navigationItem.backBarButtonItem = UIBarButtonItem(title: "Back", style: .plain, target: nil, action: nil)
    }
}

并从中继承:

class YourViewController: BaseClass { ... }