【问题标题】:How to center custom view from xib in navigationItem titleView如何在 navigationItem titleView 中将来自 xib 的自定义视图居中
【发布时间】:2018-02-10 16:47:03
【问题描述】:

我创建了带有中心垂直+中心水平约束的xib文件,稍后将成为navigationItem的titleView。

在 xib 的 init 中,我设置了文本和图像。

class UIViewFromNib: UIView {
    @IBOutlet var view: UIView!
    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var titleImageView: UIImageView!
    init(frame: CGRect,title:String,image:UIImage) {
        super.init(frame: frame)
        UINib(nibName: "NavTitle", bundle: nil)
            .instantiate(withOwner: self, options: nil)
        addSubview(view)
        view.frame = self.bounds
        titleLabel.text = title
        titleImageView.image = image
    }
}

然后,在videDidLoad 中,我将视图添加到navigationItem 的titleView 中。

    let rect = CGRect(x: 0, y: 0, width: width, height: 40)
    let width = self.view.bounds.width
    let view = UIViewFromNib(frame: rect,
                             title:  title,
                             image: image)

    navigationItem.titleView = view
    navigationItem.titleView?.sizeToFit()

但在运行时视图不在中心。

在 RTL 中更糟

我该如何解决? 谢谢

【问题讨论】:

    标签: ios swift swift3 uinavigationcontroller


    【解决方案1】:

    支持自动布局。

        let screenWidth = UIScreen.main.bounds.size.width
        let viewWidth = 200.0
        let rect = CGRect(x: (Double)(screenWidth/2)-(Double)(viewWidth/2), y: 0, width: viewWidth, height: 40)
    

    【讨论】:

      【解决方案2】:

      尝试更改此行:

      let rect = CGRect(x: 0, y: 0, width: width, height: 40)
      

      let rect = CGRect(x: 0, y: 0, width: 200, height: 40)
      

      问题是您将屏幕宽度赋予视图。在运行时,当返回按钮出现时,视图宽度会更改为 (totalWidth - navigationBackButtonWidth),这会更改其中图像的中心对齐方式。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多