如何从导航项中的xib自定义视图中心titleView
问题描述:
我创建了具有中心垂直+中心水平约束的xib文件,稍后将作为navigationItem的titleView。 如何从导航项中的xib自定义视图中心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更糟
我怎样才能解决呢? 感谢
答
支持自动布局。
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)
答
尝试修改此行:
let rect = CGRect(x: 0, y: 0, width: width, height: 40)
到
let rect = CGRect(x: 0, y: 0, width: 200, height: 40)
问题是你给屏幕的宽度与视图。在运行时,当返回按钮出现时,视图宽度变为(totalWidth - navigationBackButtonWidth),它改变其中图像的中心对齐。