How to achieve UIButton / UILabel 'padding' in iPhone app

前端 未结 10 2065
挽巷
挽巷 2021-01-31 13:40

I\'ve got various views in my iPhone application that require padding e.g a custom UIButton with text aligned left, and a UILabel with a background color.

This may be a

10条回答
  •  北恋
    北恋 (楼主)
    2021-01-31 13:55

    Here's a sublass of UILabel that has customizable padding using an edgeInset property:

    PaddedLabel.h

    #import 
    @interface PaddedLabel : UILabel
    @property UIEdgeInsets edgeInsets;
    @end
    

    PaddedLabel.m

    #import "PaddedLabel.h"
    @implementation PaddedLabel
    -(void)drawTextInRect:(CGRect)rect {
        return [super drawTextInRect:UIEdgeInsetsInsetRect(rect, self.edgeInsets)];
    }
    -(CGSize)intrinsicContentSize {
        CGSize contentSize = [super intrinsicContentSize];
        UIEdgeInsets insets = self.edgeInsets;
        contentSize.height += insets.top + insets.bottom;
        contentSize.width += insets.left + insets.right;
        return contentSize;
    }
    @end
    

    (This is a simplification of Brody's answer which also works with autolayout.)

提交回复
热议问题