自適應一般分為2種 label和button的文字自適應
下面分情況說明
>比較古老的方法 (封裝 傳入字體大小 和文本內容)
label.numberOfLines = 0; //自動換行
label.font = [UIFont systemFontOfSize:14];
label.textAlignment = NSTextAlignmentLeft;
label.text = @"iOS之行在路上";
CGSize size = [self sizeWithString:label.text font:label.font]; //2個參數 文本和字體
label.bounds = CGRectMake(0, 0, size.width, size.height);
- (CGSize)sizeWithString:(NSString *)string font:(UIFont *)font
{
CGRect rect = [string boundingRectWithSize:CGSizeMake(200, 300) //限制最大的寬度和高度
options:NSStringDrawingTruncatesLastVisibleLine |? NSStringDrawingUsesFontLeading | NSStringDrawingUsesLineFragmentOrigin //采用換行模式
attributes:@{NSFontAttributeName:font} //傳入字體
context:nil];
return rect.size;
}
>根據字體得到NSString的大小? sizeWithAttributes(這個方法)
UIFont *fnt = [UIFont fontWithName:@"HelveticaNeue" size:14];
self.TextLabel.font = fnt;
CGSize size = [self.TextLabel.text sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:fnt,NSFontAttributeName, nil]];
self.TextLabel.frame=CGRectMake(self.goodsImg.frame.origin.x+self.goodsImg.bounds.size.width+8, 69, size.width, 18);
>label 自適應方法
UILabel? *label =[UILabel alloc] init];
label.frame =CGRectMake(0,0,width, 30);
label.numberOfLine=0;
label.text =@"11111111111111111111111111111111111";
[label sizeToFit];