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

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

    What about creating a custom class that extends UIButton and overriding this:

    - (CGRect)titleRectForContentRect:(CGRect)contentRect
    {
        return UIEdgeInsetsInsetRect(contentRect, UIEdgeInsetsMake(topPadding, rightPadding, bottomPadding, leftPadding));
    }
    

    In the case of UILabel just override:

    - (CGRect)textRectForBounds:(CGRect)bounds 
         limitedToNumberOfLines:(NSInteger)numberOfLines;
    
    0 讨论(0)
  • 2021-01-31 13:50

    On Xcode 9, the insets are now located in the Size Inspector instead of the Attributes Inspector:

    0 讨论(0)
  • 2021-01-31 13:54

    If you're just looking for a horizontal padding on one line, then this may be enough (it was for me):

    NSString* padding = @"  "; // 2 spaces
    myLabel.text = [NSString stringWithFormat:@"%@%@%@", padding, name, padding];
    
    0 讨论(0)
  • 2021-01-31 13:55

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

    PaddedLabel.h

    #import <UIKit/UIKit.h>
    @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.)

    0 讨论(0)
  • 2021-01-31 13:59

    I'm trying to achieve a similar thing, that is 'pad' a UILabel. I've been trying to implement the solution that Toby posted above, but can't seem to find where this needs to go. The UILabel I'm working with is aligned left - is that what's causing the issue?

    I've tried using this in viewDidLoad, and even in a subclass of UILabel in the method:

    - (CGRect)textRectForBounds:(CGRect)bounds
         limitedToNumberOfLines:(NSInteger)numberOfLines 
    0 讨论(0)
  • 2021-01-31 14:02

    I am using auto layout. Solution that worked for me was setting UIButton's contentEdgeInsets.

    ObjC

    button.contentEdgeInsets = UIEdgeInsetsMake(0.0f, 30.0f, 0.0f, 30.0f);
    

    Swift

    button.contentEdgeInsets = UIEdgeInsets(top: 0.0, left: 30.0, bottom: 0.0, right: 30.0)
    
    0 讨论(0)
提交回复
热议问题