您的位置:首页 > 产品设计 > UI/UE

UILabel的自适应高度iOS7.0以上版本

2015-03-07 10:01 344 查看
看到别的博客写的自适应方法用了下却不能用:

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0,0,0,0)];这个frame是初设的,没关系,后面还会重新设置其size。

[label setNumberOfLines:0];

NSString *s = @"string......";

UIFont *font = [UIFont fontWithName:@"Arial" size:12];

CGSize size = CGSizeMake(320,2000);

CGSize labelsize = [s sizeWithFont:font constrainedToSize:size lineBreakMode:UILineBreakModeWordWrap];

[label setFrame:CGRectMake:(0,0, labelsize.width, labelsize.height)];

[self.view addSubView:label];

这样就可以对s赋值让其自动调整其大小了。

进入API看了下才发现问题:NS_DEPRECATED_IOS(2_0, 7_0, "Use -boundingRectWithSize:options:attributes:context:");

这个方法只能在ios2.0--iOS7.0版本之间使用,我的版本较高,需要使用:-boundingRectWithSize:options:attributes:context:方法:

UILabel的自适应高度的方法:

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10,200,100,50)];

label.numberOfLines = 0;

NSDictionary *strAtt = @{NSFontAttributeName:[UIFont systemFontOfSize:17]};

NSString *value = @"hxdksa noasd njkla n";

CGFloat width = [[UIScreen mainScreen] bounds].size.width;

CGRect rectStr = [value boundingRectWithSize:CGSizeMake(width, 10000) options:NSStringDrawingUsesLineFragmentOrigin attributes:strAtt context:nil];

label.frame = CGRectMake(label.frame.origin.x, label.frame.origin.y, label.frame.size.width, rectStr.size.height);

[label sizeToFit];

[self.view addSubview:label];

[label release];

问题解决!!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: