为何用作UIBarButtonItem的UIButton高度无法改变?
Hey there! Let's figure out why your UIButton's height isn't cooperating and get that perfect circle working for your UIBarButtonItem.
Why Your Button Height Isn't Adjusting
A few missteps are causing the issue:
- You’re modifying
hasMessageBtn.layer.frameinstead of the button’s ownframe. The layer’s frame is tied to the button’s bounds, so tweaking it directly won’t change the button’s actual visible size. - You initialized the button with just
[UIButton alloc]but skipped calling an init method likeinitWithFrame:. That leaves the button with an undefined initial size, which makes it hard to control later. - UIBarButtonItem applies its own Auto Layout constraints to custom views. Hardcoding frames can get overridden by these system constraints, leading to unexpected sizing.
Fixed Code for the Perfect Circle Button
Here’s the corrected implementation with best practices:
// 1. Properly initialize the button with a defined frame UIButton *hasMessageBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 24, 24)]; hasMessageBtn.backgroundColor = [UIColor orangeColor]; // 2. Set up the rounded corners correctly hasMessageBtn.layer.cornerRadius = hasMessageBtn.bounds.size.width / 2; // Dynamic radius for perfect circle hasMessageBtn.layer.masksToBounds = YES; // Critical to clip the button to the rounded shape // 3. Add your tap action [hasMessageBtn addTarget:self action:@selector(openMessages:) forControlEvents:UIControlEventTouchUpInside]; // 4. Lock in the size with Auto Layout (prevents UIBarButtonItem from resizing it) hasMessageBtn.translatesAutoresizingMaskIntoConstraints = NO; [NSLayoutConstraint activateConstraints:@[ [hasMessageBtn.widthAnchor constraintEqualToConstant:24], [hasMessageBtn.heightAnchor constraintEqualToConstant:24] ]]; // 5. Create the UIBarButtonItem with your custom button UIBarButtonItem *messages = [[UIBarButtonItem alloc] initWithCustomView:hasMessageBtn];
Quick Tips to Remember
- Always use a proper init method (like
initWithFrame:) for UIButton to set its initial dimensions. - Using
bounds.size.width / 2for corner radius means your button stays a perfect circle even if you adjust its size later, no hardcoding needed. - Don’t forget
masksToBounds = YES— without it, the button’s content will bleed outside the rounded corners, and you won’t see the circle effect. - Adding explicit width/height constraints ensures UIBarButtonItem doesn’t override your desired size, which is a common gotcha with custom bar button items.
内容的提问来源于stack exchange,提问作者Austin Berenyi
相关产品推荐
相关产品推荐

