1. 程式人生 > >ios開發中計算字串的高度

ios開發中計算字串的高度

//第一種演算法,ios7.0後已經廢棄

CGSize titleSize = [aString sizeWithFont:font constrainedToSize:CGSizeMake(@"label的寬度", MAXFLOAT) lineBreakMode:UILineBreakModeWordWrap];

//第二種演算法ios7.0 後計算字串的高度

CGRect rect = [aString boundingRectWithSize:CGSizeMake(@"label的寬度", MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : font} context:nil
]; NSLog(@"Height:::%f",rect.size.height);

封裝

//此處1000為高度 還可以換為:MAXFLOAT

-(void)ViewDidload{

CGSizestringSize=[self sizeWithFont:font maxSize:CGSizeMake(SCREEN_WIDTH-20, 1000)string:aString];

float  textH= stringSize.height;

NSLog(@"textH:::%f",textH);

}

-(CGSize)sizeWithFont:(UIFont *)font maxSize:(CGSize
)maxSize string:(NSString *)string{ NSDictionary *attrs = @{NSFontAttributeName:font}; return [string boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size; }