NSString * myText = [NSString stringWithString:@"some text"];
//獲取到文本大大小
CGFloat constrainedSize = 265.0f; //其他大小也行
UIFont * myFont = [UIFont fontWithName:@"Arial" size:19]; // UILabel使用的字體
CGSize textSize = [myText sizeWithFont: myFont
constrainedToSize:CGSizeMake(constrainedSize, CGFLOAT_MAX)
lineBreakMode:UILineBreakModeWordWrap];
textSize.width
textSize.height
即為UILable的寬和高,
CGRect labelFrame = CGRectMake (0, 0, textSize.width, textSize.height);
UILabel *label = [[UILabel alloc] initWithFrame:labelFrame];
即可用到
工整一些做法:
[cpp]
- //計算文本所占高度
- //2個參數:寬度和文本內容
- -(CGFloat)calculateTextHeight:(CGFloat)widthInput Content:(NSString *)strContent{
- CGSize constraint = CGSizeMake(widthInput, 20000.0f);
- CGSize size = [strContent sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
- CGFloat height = MAX(size.height, 44.0f);
- return height;
- }
-
- //計算 寬度
- -(CGFloat)calculateTextWidth:(NSString *)strContent{
- // CGSize constraint = CGSizeMake(heightInput, heightInput);
- CGFloat constrainedSize = 26500.0f; //其他大小也行
- CGSize size = [strContent sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:CGSizeMake(constrainedSize, CGFLOAT_MAX) lineBreakMode:UILineBreakModeWordWrap];
- // CGFloat height = MAX(size.height, 44.0f);
- return size.width;
- }