UILabel文本边距
我正在寻找设置UILabel
的左侧插入/边界,并找不到一个方法来做到这一点。 该标签有一个背景设置,所以只是改变它的来源不会做到这一点。 将文本插入左侧10px
左右是理想的。
我通过UILabel
并重写drawTextInRect:
解决了这个问题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))
}
正如你可能已经收集到的,这是tc。答案的改编。 它有两个优势:
sizeToFit
消息来触发它 对于多行文本,可以使用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;
将填充添加到UILabel的最佳方法是继承UILabel并添加edgeInsets属性。 然后设置所需的插图,并相应地绘制标签。
OSLabel.h
#import <UIKit/UIKit.h>
@interface OSLabel : UILabel
@property (nonatomic, assign) UIEdgeInsets edgeInsets;
@end
OSLabel.m
#import "OSLabel.h"
@implementation OSLabel
- (id)initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
if (self) {
self.edgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
}
return self;
}
- (void)drawTextInRect:(CGRect)rect {
[super drawTextInRect:UIEdgeInsetsInsetRect(rect, self.edgeInsets)];
}
- (CGSize)intrinsicContentSize
{
CGSize size = [super intrinsicContentSize];
size.width += self.edgeInsets.left + self.edgeInsets.right;
size.height += self.edgeInsets.top + self.edgeInsets.bottom;
return size;
}
@end
链接地址: http://www.djcxy.com/p/4835.html
上一篇: UILabel text margin