直接對 UILabel 的 layer 加邊框:
label.layer.borderColor = [UIColor grayColor].CGColor;
label.layer.borderWidth = 2;
文字會緊貼邊框,無視覺呼吸空間。
@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
InsetLabelInsetLabel *label = [[InsetLabel alloc] init];@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; 讓文字在內縮區域內置中,效果更佳。