在UITableView中的自动布局中带有填充的多行UILabel



我在UITableView中有一个UILabel,它最多应该有2行,周围有一些填充(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];
}

它在表格视图中有区别吗?如有任何帮助,我们将不胜感激。

正如您在我上面的评论中看到的,您并没有真正说出它在做什么,这是您没有预料到的。我刚刚自己做了这件事,这件事适用于自动布局:

@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
@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];
}

这比imho效果更好。

最新更新