我使用以下代码制作了可变尺寸UILabel
但我想将最大宽度设置为label
你有什么想法吗?
- (void)viewDidLoad {
CGSize size = [self labelFrameWithString:@"test text"];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, size.width. size.height];
label.text = @"test text";
}
- (CGSize)labelFrameWithString:(NSString *)string {
CGRect frame = [string boundingRectWithSize:CGSizeZero
options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingTruncatesLastVisibleLine)
attributes:[NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:16] forKey:NSFontAttributeName]
context:nil];
return frame.size;
}
答案 0 :(得分:1)
您是否尝试传递受约束的CGSize而不是CGSizeZero?
CGSize constraint = CGSizeMake(your_max_width ,NSUIntegerMax);
CGRect frame = [string boundingRectWithSize:constraint
options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingTruncatesLastVisibleLine)
attributes:[NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:16] forKey:NSFontAttributeName]
context:nil];