自動計算高度和寬度的關鍵點無外乎三個因素,文字內容,寬度或高度,再者就是字號,通過這三個因素,去自動計算對應的高度或寬度
自動計算高度
-(CGRect)contentRectWithString:(NSString *)string labelWidth:(CGFloat)labelWidth AndStringFont:(int)fontSize
{
CGRect tempRect = [string boundingRectWithSize:CGSizeMake(labelWidth, MAXFLOAT)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:fontSize],NSFontAttributeName, nil] context:nil];
return tempRect;
}
自動計算寬度
-(CGRect)contentRectWithString:(NSString *)string labelHeight:(CGFloat)labelHeight AndStringFont:(int)fontSize
{
CGRect tempRect = [string boundingRectWithSize:CGSizeMake(MAXFLOAT, labelHeight)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:fontSize],NSFontAttributeName, nil] context:nil];
return tempRect;
}
示例代碼
#import "ViewController.h"
#import "Masonry.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UILabel *myLabel;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.myLabel = (UILabel *)[self.view viewWithTag:3];
[self.view addSubview:self.myLabel];
self.myLabel.numberOfLines = 0;
NSString *str = @"豫章故郡,洪都新府。星分翼軫,地接衡廬。襟三江而帶五湖,控蠻荊而引甌越。物華天寶,龍光射牛斗之墟;人杰地靈,徐孺下陳蕃之榻。雄州霧列,俊采星馳。臺隍枕夷夏之交,賓主盡東南之美。都督閻公之雅望,棨戟遙臨;宇文新州之懿范,襜帷暫駐。十旬休假,勝友如云;千里逢迎,高朋滿座。騰蛟起鳳,孟學士之詞宗;紫電青霜,王將軍之武庫。家君作宰,路出名區;童子何知,躬逢勝餞。時維九月,序屬三秋。潦水盡而寒潭清,煙光凝而暮山紫。儼驂騑于上路,訪風景于崇阿。臨帝子之長洲,得仙人之舊館。層巒聳翠,上出重霄;飛閣流丹,下臨無地。鶴汀鳧渚,窮島嶼之縈回;桂殿蘭宮,列岡巒之體勢。披繡闥,俯雕甍,山原曠其盈視,川澤紆其駭矚。閭閻撲地,鐘鳴鼎食之家;舸艦迷津,青雀黃龍之舳。云銷雨霽,";
CGRect labelRect = [self contentRectWithString:str labelWidth:200.0 AndStringFont:15.0];
float height = labelRect.size.height;
[self.myLabel mas_updateConstraints:^(MASConstraintMaker *make) {
make.height.mas_equalTo(height);
}];
self.myLabel.text = str;
}
-(CGRect)contentRectWithString:(NSString *)string labelWidth:(CGFloat)labelWidth AndStringFont:(int)fontSize
{
CGRect tempRect = [string boundingRectWithSize:CGSizeMake(labelWidth, MAXFLOAT)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:fontSize],NSFontAttributeName, nil] context:nil];
return tempRect;
}