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

前端 未结 10 2063
挽巷
挽巷 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

    Ok the simplest solution I've found so far is:

    self.textAlignment = UITextAlignmentCenter; 
    [self sizeToFit]; 
    CGRect frame = self.frame;
    frame.size.width += 20; //l + r padding 
    self.frame = frame;
    

    Not exactly what I wanted, but it works.

    0 讨论(0)
  • 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 <UIKit/UIKit.h>
    
    @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
    
    0 讨论(0)
  • 2021-01-31 14:14

    To set padding in UIButton text you need to use UIButton's contentEdgeInsets property.

    In Storyboard, to set content inset do following steps:

    1. Select the view controller, then select the UIButton
    2. Go to Utilities Panel (Command + Option + 0) and select Attributes Inspector (Command + Option + 4)
    3. Now select Content in Edge and set Inset as per your requirement (see screenshot)

    0 讨论(0)
  • 2021-01-31 14:14

    CGRectInset is your friend. You can set negative 'insets' to create padding:

    [self sizeToFit];
    CGRect rect = self.frame;
    rect = CGRectInset( rect, -6.f, -5.f); // h inset, v inset
    self.frame = rect;
    
    0 讨论(0)
提交回复
热议问题