UILabel文字邊距我正在設置a的左邊插入/邊距,UILabel但找不到這樣做的方法。標簽有一個背景設置,所以只是改變它的起源不會有效。10px左手邊左右插入文本是理想的。
3 回答

POPMUISE
TA貢獻1765條經驗 獲得超5個贊
我通過子類化UILabel
和覆蓋解決了這個問題drawTextInRect:
:
- (void)drawTextInRect:(CGRect)rect { UIEdgeInsets insets = {0, 5, 0, 5}; [super drawTextInRect:UIEdgeInsetsInsetRect(rect, insets)];}
Swift 3.1:
override func drawText(in rect: CGRect) { let insets = UIEdgeInsets.init(top: 0, left: 5, bottom: 0, right: 5) super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))}
Swift 4.2.1:
override func drawText(in rect: CGRect) { let insets = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5) super.drawText(in: rect.inset(by: insets))}
正如你可能已經聚集的那樣,這是對tc。答案的改編。它有兩個優點:
沒有必要通過發送
sizeToFit
消息來觸發它它會單獨留下標簽框 - 如果您的標簽有背景并且您不希望它縮小,則很方便

慕后森
TA貢獻1802條經驗 獲得超5個贊
對于多行文本,可以使用NSAttributedString設置左邊距和右邊距。
NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];style.alignment = NSTextAlignmentJustified;style.firstLineHeadIndent = 10.0f;style.headIndent = 10.0f;style.tailIndent = -10.0f; NSAttributedString *attrText = [[NSAttributedString alloc] initWithString:title attributes:@{ NSParagraphStyleAttributeName : style}]; UILabel * label = [[UILabel alloc] initWithFrame:someFrame];label.numberOfLines = 0;label.attributedText = attrText;
- 3 回答
- 0 關注
- 916 瀏覽
添加回答
舉報
0/150
提交
取消