首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

iOS UILabel 加邊框後文字貼邊?自定義繪製實現內邊距

     編輯:程式設計綜合問答

現象

直接對 UILabel 的 layer 加邊框:

label.layer.borderColor = [UIColor grayColor].CGColor;
label.layer.borderWidth = 2;

文字會緊貼邊框,無視覺呼吸空間。

解決方案:繼承 UILabel 重寫 drawTextInRect:

@interface InsetLabel : UILabel
@end

@implementation InsetLabel
- (void)drawTextInRect:(CGRect)rect {
    UIEdgeInsets insets = UIEdgeInsetsMake(10, 10, 10, 10); // 上左下右
    CGRect newRect = UIEdgeInsetsInsetRect(rect, insets);
    [super drawTextInRect:newRect];
}
@end

使用方式

  • Storyboard/XIB 中將 Label Class 改為 InsetLabel
  • 或程式碼建立:InsetLabel *label = [[InsetLabel alloc] init];

進階:支援 Interface Builder 即時調整

@IBDesignable
class InsetLabel: UILabel {
    @IBInspectable var insetTop: CGFloat = 10
    @IBInspectable var insetLeft: CGFloat = 10
    @IBInspectable var insetBottom: CGFloat = 10
    @IBInspectable var insetRight: CGFloat = 10

    override func drawText(in rect: CGRect) {
        let insets = UIEdgeInsets(top: insetTop, left: insetLeft, bottom: insetBottom, right: insetRight)
        super.drawText(in: rect.inset(by: insets))
    }

    override var intrinsicContentSize: CGSize {
        var size = super.intrinsicContentSize
        size.width += insetLeft + insetRight
        size.height += insetTop + insetBottom
        return size
    }
}

(Swift 版本,同理可用 Objective-C 實現 intrinsicContentSize)

補充:文字置中

配合 label.textAlignment = NSTextAlignmentCenter; 讓文字在內縮區域內置中,效果更佳。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved