简体   繁体   中英

Constrain a view to position of a UIBarButtonItem

I want a label to be floating above a toolbar's UIBarButtonItem. I have been able to constrain it so that it is right above the toolbar, but I can't figure out how to make it's center.x to match the center.x of the UIBarButtonItem. How can I do this with AutoLayout?

You cannot do do this with UIBarButtonItem .

With UIButton you can click the label or button and then Control drag to the other and select "Center x" option

I ended up solving this in the following way:

(Since the UIBarButtonItem is not a view, you cannot add constraints directly to it. So, we use valueForKey: to retrieve the view)

if let itemView = myBarButtonItem.valueForKey("view") as? UIView {
        view.addConstraint(NSLayoutConstraint(item: myLabel,
            attribute: .CenterX,
            relatedBy: .Equal,
            toItem: itemView,
            attribute: .CenterX,
            multiplier: 1,
            constant: 0))
}

NOTE: I only tested this with a toolbar I manually added to the view, it will not work with the navigation controller's toolbar

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