您的位置:首页 > 移动开发 > IOS开发

iOS - 固定宽度和字号,获取Label的frame;固定高度和字号,获取Label的frame

2016-01-22 13:06 495 查看
固定宽度和字号,获取Label的frame;固定高度和字号,获取Label的frame

效果图:



代码如下:

- (void) loadSet

{

UILabel * textLabel = [[UILabel alloc]init];

NSString * str = @"天将降大任于斯人也,必先苦其心志,劳其筋骨,饿其体肤,空乏其身,行夫乱其所为。";

CGSize size = [self getSizeWithStr:str Width:200 Font:20];

textLabel.frame = CGRectMake(20, 90, 200, size.height);

textLabel.text = str;

textLabel.numberOfLines = 0;

textLabel.backgroundColor = [UIColor redColor];

[self.view addSubview:textLabel];

UILabel * textLabel1 = [[UILabel alloc]init];

NSString * str1 = @"temp";

CGSize size1 = [self getSizeWithStr:str1 Height:20 Font:20];

textLabel1.frame = CGRectMake(20, 300, size1.width, 20);

textLabel1.text = str1;

textLabel1.backgroundColor = [UIColor redColor];

[self.view addSubview:textLabel1];

}

#pragma mark - 固定宽度和字体大小,获取label的frame

- (CGSize) getSizeWithStr:(NSString *) str Width:(float)width Font:(float)fontSize

{

NSDictionary * attribute = @{NSFontAttributeName:[UIFont systemFontOfSize:fontSize]};

CGSize tempSize = [str boundingRectWithSize:CGSizeMake(width, MAXFLOAT)

options:NSStringDrawingUsesLineFragmentOrigin

attributes:attribute

context:nil].size;

return tempSize;

}

#pragma mark - 固定高度和字体大小,获取label的frame

- (CGSize) getSizeWithStr:(NSString *) str Height:(float)height Font:(float)fontSize

{

NSDictionary * attribute = @{NSFontAttributeName :[UIFont systemFontOfSize:fontSize] };

CGSize tempSize=[str boundingRectWithSize:CGSizeMake(MAXFLOAT, height)

options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading

attributes:attribute

context:nil].size;

return tempSize;

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