简体   繁体   中英

How to center custom view from xib in navigationItem titleView

I created xib file with center vertical + center horizontal constraints that will be the titleView of navigationItem later. 在此处输入图片说明

inside the init of the xib I set the text and the image.

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
    }
}

Then, inside the videDidLoad I add the view into the titleView of navigationItem.

    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()

but at runtime the view is not in the center. LTR

In RTL even worse

RTL

How can I fix it ? Thanks

Support auto layout.

    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)

Try changing this line:

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

to

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

The problem is you are giving width of the screen to the view. At run time when back button appears view width changes to (totalWidth - navigationBackButtonWidth) which changes the centre alignment of the images inside it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM