Cropped UIButton Title

2019-01-26 15:20发布

问题:

I am using a custom font for the title of a UIButton. It works, except with this particular font a portion of the first character is clipped. For example:

I tried setting the contentEdgeInsets and titleEdgeInsets and can't seem to get it not clipped. I also tried setting the button.titleLabel.clipsToBounds property to NO;

Any suggestions would be greatly appreciated.

回答1:

Although Jeshua's solution works fine, it's not an optimal in my eyes. I'd rather recommend to subclass UIButton and overwrite it's layoutSubviews Method.

-(void)layoutSubviews
{
    [super layoutSubviews];

    CGRect frame = self.titleLabel.frame;
    frame.size.height = self.bounds.size.height;
    frame.origin.y = self.titleEdgeInsets.top;
    self.titleLabel.frame = frame;
}


回答2:

So I just ended up setting the UIButton title to nil and added my own UILabel as a subview to the UIButton. I set the UILabel frame to the same size as the button and set it to be centered.

Not the most elegant solution I am sure, but it gets the job done.



回答3:

It looks to me like your content is aligned funkily. If the frame of the label is not directly accessible, use [button setContentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter]; to try to fix the horizontal alignment issue.



回答4:

Swift code for above answer:

override func layoutSubviews() {
    super.layoutSubviews()
    titleLabel?.frame = CGRect(x: bounds.origin.x, y: titleEdgeInsets.top, width: frame.width, height: bounds.size.height)
}