計算文字高度
阿新 • • 發佈:2018-12-13
計算文字高度
label
//定義label self.titleLabel = [[UILabel alloc] init]; NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init]; [style setLineSpacing:2]; NSDictionary *dic = @{NSFontAttributeName:[UIFont fontWithName:@"PingFangSC-Light" size:14], NSParagraphStyleAttributeName:style}; NSAttributedString *attributeStr = [[NSAttributedString alloc] initWithString:self.nameStr attributes:dic]; self..titleLabel.attributedText = attributeStr; CGFloat height = [self getHeightLineWithString:self.nameStr withWidth:kScreenWidth - 30 withFont:[UIFont fontWithName:@"PingFangSC-Light" size:14]]; self..titleLabel.frame = CGRectMake(15, kNavgationHeight, kScreenWidth - 30, height);
根據字串計算label高度
#pragma mark - 根據字串計算label高度 - (CGFloat)getHeightLineWithString:(NSString *)string withWidth:(CGFloat)width withFont:(UIFont *)font { //1.1最大允許繪製的文字範圍 CGSize size = CGSizeMake(width, 2000); //1.2配置計算時的行擷取方法,和contentLabel對應 NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init]; [style setLineSpacing:2]; //1.3配置計算時的字型的大小 //1.4配置屬性字典 NSDictionary *dic = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:style}; //2.計算 //如果想保留多個列舉值,則列舉值中間加按位或|即可,並不是所有的列舉型別都可以按位或,只有列舉值的賦值中有左移運算子時才可以 CGFloat height = [string boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:dic context:nil].size.height; return height; }