我们在做App的过程中有时UI设计的一些界面上的文字只给出了其距离左右的间距,以及文字的大小,并没有给出文字的长和宽,这时我们需要利用Label的自适应。其实利用label的自适应更多的情况是label上的文字并并不确定,如用户名,这时更需要我们利用label的自适应。
代码如下:
UILabel * attentionLbl = [[UILabel alloc] init];
attentionLbl.backgroundColor = [UIColor redColor];
attentionLbl.font = [UIFont systemFontOfSize:17];
attentionLbl.textColor = [UIColor colorWithRed:255 / 255.0 green:255 / 255.0 blue:255 / 255.0 alpha:1];
attentionLbl.text = @"关住";
CGFloat attentionX = 0;
CGFloat attentionY = 20;
NSMutableDictionary * attentionDic = [NSMutableDictionary dictionary];
attentionDic[NSFontAttributeName] = [UIFont systemFontOfSize:17];
CGSize attentionSize = [attentionLbl.text sizeWithAttributes:attentionDic];
attentionLbl.frame = (CGRect){{attentionX, attentionY},attentionSize};
[self.view addSubview:attentionLbl];