我在UITableView中有一个UILabel,最多应该有两行,并且周围有一些填充(左右7个,顶部和底部2个)。我正在使用自动布局,仅针对iOS6及更高版本。所有视图都以编程方式创建和添加。
我已经将我的UILabel子类化了,这是init
方法:
- (id)init
{
self = [super init];
self.translatesAutoresizingMaskIntoConstraints = NO;
self.numberOfLines = 2;
self.backgroundColor = UIColorFromARGB(0x99000000);
self.textColor = [UIColor whiteColor];
self.font = [UIFont boldSystemFontOfSize:14.0f];
return self;
}
如果我添加它,我得到正确的填充,但它只使它成为一行:
- (void)drawTextInRect:(CGRect)rect {
UIEdgeInsets insets = {2, 7, 2, 7};
return [super drawTextInRect:UIEdgeInsetsInsetRect(rect, insets)];
}
我已经看过几次这个答案,但它对我不起作用(没有效果):
- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines
{
UIEdgeInsets insets = {2, 7, 2, 7};
return [super textRectForBounds:UIEdgeInsetsInsetRect(bounds,insets) limitedToNumberOfLines:numberOfLines];
}
它是否在表视图中有所不同?任何帮助将不胜感激。
答案 0 :(得分:9)
正如你在上面的评论中所看到的那样,你并没有真正说出你没想到的是什么。我自己就是这样做的,这适用于autolayout:
@implementation InsetLabel
- (void) setInsets:(UIEdgeInsets)insets
{
_insets = insets ;
[self invalidateIntrinsicContentSize] ;
}
- (void)drawTextInRect:(CGRect)rect
{
return [super drawTextInRect:UIEdgeInsetsInsetRect(rect, self.insets)];
}
- (void)resizeHeightToFitText
{
CGRect frame = [self bounds];
CGFloat textWidth = frame.size.width - (self.insets.left + self.insets.right);
CGSize newSize = [self.text sizeWithFont:self.font constrainedToSize:CGSizeMake(textWidth, 1000000) lineBreakMode:self.lineBreakMode];
frame.size.height = newSize.height + self.insets.top + self.insets.bottom;
self.frame = frame;
}
- (CGSize) intrinsicContentSize
{
CGSize superSize = [super intrinsicContentSize] ;
superSize.height += self.insets.top + self.insets.bottom ;
superSize.width += self.insets.left + self.insets.right ;
return superSize ;
}
@end
答案 1 :(得分:2)
@implementation InsetLabel
- (void) setInsets:(UIEdgeInsets)insets
{
_insets = insets ;
[self invalidateIntrinsicContentSize] ;
}
- (void)drawTextInRect:(CGRect)rect
{
return [super drawTextInRect:UIEdgeInsetsInsetRect(rect, self.insets)];
}
- (void)resizeHeightToFitText
{
CGRect frame = [self frame];
CGFloat textWidth = frame.size.width - (self.insets.left + self.insets.right);
CGSize newSize = [self.text sizeWithFont:self.font constrainedToSize:CGSizeMake(textWidth, 1000000) lineBreakMode:self.lineBreakMode];
frame.size.height = newSize.height + self.insets.top + self.insets.bottom;
self.frame = frame;
}
- (CGSize) intrinsicContentSize
{
CGSize superSize = [super intrinsicContentSize] ;
superSize.height += self.insets.top + self.insets.bottom ;
superSize.width += self.insets.left + self.insets.right ;
return superSize ;
}
- (void)layoutSubviews
{
[super layoutSubviews];
[self resizeHeightToFitText];
}
这样做的效果更好。