1. 程式人生 > >iOS UILabel自適應寬度

iOS UILabel自適應寬度

UILabel * label = [[UILabelalloc]initWithFrame:CGRectMake(100, 100, 80, 20)];

    label.backgroundColor = [UIColor whiteColor];

    label.textColor = [UIColor blackColor];

    label.text = @"很久很久查詢";

    label.textAlignment = NSTextAlignmentCenter;

    codeLabel.font = [UIFontsystemFontOfSize:12];

    [self.viewaddSubview:codeLabel];


//第一種方法

CGSize size = [label.textsizeWithFont:label.fontconstrainedToSize:CGSizeMake(300, label.frame.size.height)];

//第二種方法

CGSize size = [label.textboundingRectWithSize:CGSizeMake(300, label.frame.size.height) options:NSStringDrawingUsesLineFragmentOriginattributes

:@{NSFontAttributeName:label.font}context:nil].size;