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

前端 未结 10 2081
挽巷
挽巷 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 14:10

    To add padding to UILabel the most flexible approach is to subclass UILabel and add an edgeInsets property. You then set the desired insets and the label will be drawn accordingly.

    OSLabel.h

    #import 
    
    @interface OSLabel : UILabel
    
    @property (nonatomic, assign) UIEdgeInsets edgeInsets;
    
    @end
    

    OSLabel.m

    #import "OSLabel.h"
    
    @implementation OSLabel
    
    - (id)initWithFrame:(CGRect)frame{
        self = [super initWithFrame:frame];
        if (self) {
            self.edgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
        }
        return self;
    }
    
    -(id)initWithCoder:(NSCoder *)aDecoder{
        self = [super initWithCoder:aDecoder];
        if(self){
            self.edgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
        }
        return self;
    }
    
    - (void)drawTextInRect:(CGRect)rect {
        return [super drawTextInRect:UIEdgeInsetsInsetRect(rect, self.edgeInsets)];
    }
    
    @end
    

提交回复
热议问题