CGSize stringSize = [datastring sizeWithFont:[UIFont systemFontOfSize:17]
constrainedToSize:CGSizeMake(canputwidth,CGFLOAT_MAX)
lineBreakMode:NSLineBreakByWordWrapping];
說明:計算datastring在17字體大小下,擺在canputwidth的寬度中,並且以文字換行的方式計算CGSize。
獲得CGSize後即可由stringSize.width與stringSize.height取得需要的寬高,在利用setFrame來重新給定UILabel的高度。
程式碼:
-(void)someMethod:(NSString*)name
{
int fontsize = 17;
CGSize labSize = [self calwordH:name canputwidth:self.view.bounds.size.width];
UILabel *fieldlb = [[UILabel alloc] init];
fieldlb.font = [UIFont systemFontOfSize:fontsize];
fieldlb.backgroundColor = color;
fieldlb.text = name;
[fieldlb setNumberOfLines:0];
fieldlb.lineBreakMode = NSLineBreakByWordWrapping;
[fieldlb setFrame:CGRectMake(0.0f,0.0f,labSize.width,labSize.height)];
[self.view addSubview:fieldlb];
}
-(CGSize) calwordH:(NSString *)string canputwidth:(int)canputwidth
{
CGSize s = [string sizeWithFont:[UIFont systemFontOfSize:17]
constrainedToSize:CGSizeMake(canputwidth,CGFLOAT_MAX)
lineBreakMode:NSLineBreakByWordWrapping];
return s;
}
iOS6以後NSLineBreakByWordWrapping改為NSLineBreakByWordWrapping。
沒有留言:
張貼留言