如何使用不同的颜色快速设置导航栏后退Arrow和backBarButtonItem标题

时间:2018-10-02 17:31:44

标签: ios swift uinavigationcontroller uinavigationbar

我试图设置带有箭头图像和backBarButtonItem标题的详细视图控制器导航栏,如下所示

enter image description here

我尝试添加如下箭头图像。

let imgBackArrow = UIImage(named: "backArrow")
navigationController?.navigationBar.backIndicatorImage = imgBackArrow
navigationController?.navigationBar.backIndicatorTransitionMaskImage = imgBackArrow

然后我要设置黑色标题和多行标题(对于较大的文本),但是没有任何帮助。.

    let customButton = UIBarButtonItem(title: eventName, style: UIBarButtonItem.Style.plain, target: self, action: nil)
customButton.tintColor = UIColor.black; //giving me black image as well
    self.navigationController?.navigationBar.topItem?.backBarButtonItem  = customButton

1 个答案:

答案 0 :(得分:0)

只需为导航栏创建一个自定义类。例如customNavigationBar和用于UIView的xib,并在xib中采用按钮设置其图像并采用标签并给出约束... 并在您的ViewController上放置一个UIView并将其放在顶部,并给类名称customNavigationBar

customNavigationBar类

 import UIKit

 class customNavigationBar: UIView {

 //Mark:- Iboutlets
 @IBOutlet weak var backButton: UIButton!
 @IBOutlet weak var titleLabel: UILabel!
 @IBOutlet var containerView: UIView!



 //Mark:- Lifecycle

 override init(frame: CGRect) {
 super.init(frame: frame)
 commonInit()
 }

 required init?(coder aDecoder: NSCoder) {
 super.init(coder: aDecoder)
 commonInit()
 }


 }
 //Mark:- Function

 extension customNavigationBar{
 private func commonInit(){
 Bundle.main.loadNibNamed("customNavigationBar", owner: self, options: nil)
 addSubview(containerView)
 containerView.frame = self.bounds
 containerView.autoresizingMask = [.flexibleHeight , .flexibleWidth]
 }
 }

并且您的xib文件的所有者名称必须为customNavigationBar

现在在您的ViewController类中

class ViewController: UIViewController{
@IBOutlet weak var navigationBar: customNavigationBar!

     override func viewDidLoad() {
            super.viewDidLoad()
            navigationBar.titleLabel.text = "Texas Rangers at"
            navigationBar.titleLabel.textColor = .blue
            navigationBar.backButton.addTarget(self, action : #selector(backButtonTapped), for: .touchUpInside)
        }

        @objc func backButtonTapped() {
        self.navigationController?.popViewController(animated: true)
    }

现在,这个customNavigationBar视图可以使用任何viewController,而不必每次在每个viewController中设置navigationBar