Reputation: 1375
I created a UIBarButtonItem
with a custom view using the following code (I specify the size of the profileImageButton
frame to have dimensions 40x40).
let profileImageButton = UIButton(type: .custom)
profileImageButton.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
profileImageButton.setImage(imageCache.getProfileImage(), for: .normal)
profileImageButton.layer.cornerRadius = 20
profileImageButton.layer.masksToBounds = true
profileImageButton.addTarget(self, action: #selector(self.openSettings), for: .touchUpInside)
let settingsButton = UIBarButtonItem(customView: profileImageButton)
On most devices, the view has a 40x40 frame. However, when I run it on the iPhone 6s, it looks a bit rectangular. So I printed out its frame in the debug hierarchy feature of Xcode. The result I get is: frame = (0 0; 50 44)
, which I assume means that the frame has dimensions 50x44. Therefore, my question is why doesn't the iPhone 6s keep the specified 40x40 size?
Upvotes: 0
Views: 82
Reputation: 1375
Adding onto matt's answer, I needed to also add these three lines of code for use in iOS 11:
profileImageButton.translatesAutoresizingMaskIntoConstraints = false
profileImageButton.heightAnchor.constraint(equalToConstant: 40).isActive = true
profileImageButton.widthAnchor.constraint(equalToConstant: 40).isActive = true
Upvotes: 0
Reputation: 535202
In iOS 11, the size of a UIBarButtonItem with a custom view is determined by the internal constraints of the custom view. You have not provided any internal constraints, so all bets are off; you have not put yourself in charge of the bar button item's size. To do so, give profileImageButton
a width constraint and a height constraint.
Upvotes: 1