Making variable size UILabel with maximum width

254 Views Asked by At

I made variable size UILabel with following code.
But I want to set maximum width to the label.
Do you have any idea?

- (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;
}
1

There are 1 best solutions below

0
On BEST ANSWER

Have you try pass a constrained CGSize instead of 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];