3

我在 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];
}

它在表格视图中是否有区别?任何帮助,将不胜感激。

4

2 回答 2

10

正如您在我上面的评论中看到的那样,您并没有真正说出您没想到的事情。我自己刚刚完成了这个,这适用于自动布局:

@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
于 2013-09-11T22:28:08.357 回答
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];
}

恕我直言,这效果更好。

于 2015-08-28T17:00:48.993 回答