【问题标题】:How to set navigation bar back Arrow and backBarButtonItem title with different colors swift如何使用不同颜色快速设置导航栏返回箭头和backBarButtonItem标题
【发布时间】:2018-10-02 17:31:44
【问题描述】:

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

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

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

【问题讨论】:

    标签: ios swift uinavigationcontroller uinavigationbar


    【解决方案1】:

    只需为导航栏创建一个自定义类。像 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

    【讨论】:

    • 请注意.... backButton titleLabel containerView 这是从您的 xib 到 customNavigationBar 类的出口
    猜你喜欢
    • 2020-10-27
    • 1970-01-01
    • 2013-10-02
    • 1970-01-01
    • 1970-01-01
    • 2011-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多