gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 06:20:50 24 4
gpt4 key购买 nike

我在 UITableView 中有一个 UILabel,它最多应该有 2 行,并且周围有一些填充(左右 7 个,顶部和底部 2 个)。我正在使用自动版式并且仅针对 iOS6 及更高版本。所有 View 都以编程方式创建和添加。

我已经子类化了我的 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];
}

它在表格 View 中有什么不同吗?任何帮助将不胜感激。

最佳答案

正如您在我上面的评论中看到的那样,您并没有真正说明它在做什么您没有预料到的事情。我自己刚刚完成了这项工作,这适用于自动布局:

@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

关于ios - 在 UITableView 的自动布局中带有填充的多行 UILabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18558085/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com