1. 程式人生 > >自定義UILabel,設定內邊距

自定義UILabel,設定內邊距

系統的UILabel附上文字後後自動給出一定的內邊距,按照UI的設計圖需求,標籤附著文字後不能留有邊距,只能自己自定義一個沒有內邊距的UILabel。

OC版本

#import <UIKit/UIKit.h>
IB_DESIGNABLE
@interface InsetLabel : UILabel
@property (nonatomic, assign) IBInspectable CGFloat leftEdge;
@property (nonatomic, assign) IBInspectable CGFloat rightEdge;
@property (nonatomic
, assign) IBInspectable CGFloat topEdge; @property (nonatomic, assign) IBInspectable CGFloat bottomEdge; @property (nonatomic, assign) UIEdgeInsets edgeInsets; @end
#import "InsetLabel.h"
@implementation InsetLabel

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self
) { self.edgeInsets = UIEdgeInsetsMake(self.topEdge, self.leftEdge, self.bottomEdge, self.rightEdge); } return self; } // 文字區域 - (void)drawTextInRect:(CGRect)rect { self.edgeInsets = UIEdgeInsetsMake(self.topEdge, self.leftEdge, self.bottomEdge, self.rightEdge); [super drawTextInRect:UIEdgeInsetsInsetRect(rect, self
.edgeInsets)]; } // UILabel的內容區域 - (CGSize)intrinsicContentSize { self.edgeInsets = UIEdgeInsetsMake(self.topEdge, self.leftEdge, self.bottomEdge, self.rightEdge); CGSize size = [super intrinsicContentSize]; size.width += self.edgeInsets.left + self.edgeInsets.right; size.height += self.edgeInsets.top + self.edgeInsets.bottom; return size; } @end

swift版本

class UILabelPadding : UILabel {

    private var padding = UIEdgeInsetsZero

    @IBInspectable
    var paddingLeft: CGFloat {
        get { return padding.left }
        set { padding.left = newValue }
    }

    @IBInspectable
    var paddingRight: CGFloat {
        get { return padding.right }
        set { padding.right = newValue }
    }

    @IBInspectable
    var paddingTop: CGFloat {
        get { return padding.top }
        set { padding.top = newValue }
    }

    @IBInspectable
    var paddingBottom: CGFloat {
        get { return padding.bottom }
        set { padding.bottom = newValue }
    }


    // 文字區域
    override func drawTextInRect(rect: CGRect) {
        super.drawTextInRect(UIEdgeInsetsInsetRect(rect, padding))

    }

    // UILabel的內容區域
    override func textRectForBounds(bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
        let insets = self.padding
        var rect = super.textRectForBounds(UIEdgeInsetsInsetRect(bounds, insets), limitedToNumberOfLines: numberOfLines)
        rect.origin.x    -= insets.left
        rect.origin.y    -= insets.top
        rect.size.width  += (insets.left + insets.right)
        rect.size.height += (insets.top + insets.bottom)
        return rect
    }
}