Cropped UIButton Title

后端 未结 4 1896
予麋鹿
予麋鹿 2020-12-18 04:50

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:

相关标签:
4条回答
  • 2020-12-18 05:06

    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;
    }
    
    0 讨论(0)
  • 2020-12-18 05:08

    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.

    0 讨论(0)
  • 2020-12-18 05:22

    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)
    }
    
    0 讨论(0)
  • 2020-12-18 05:30

    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.

    0 讨论(0)
提交回复
热议问题