一缕碎、前言
在做項(xiàng)目的時(shí)候有計(jì)算label的寬度適配UI的要求,之前也總結(jié)了Category是計(jì)算label自適應(yīng)高度及寬度池户,然后發(fā)現(xiàn)在9系統(tǒng)下總是出現(xiàn)'...'就是顯示不全咏雌,所以在此記錄一下解決方法希望能幫助有同樣需求的人。
二校焦、之前的Category方法
#pragma mark - 計(jì)算字符串尺寸
/**
* 計(jì)算字符串高度 (多行)
*
* @param width 字符串的寬度
* @param font 字體大小
*
* @return 字符串的尺寸
*/
- (CGSize)heightWithWidth:(CGFloat)width andFont:(CGFloat)font {
NSDictionary *attribute = @{NSFontAttributeName: [UIFont systemFontOfSize:font]};
CGSize size = [self boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:(NSStringDrawingUsesFontLeading|NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin) attributes:attribute context:nil].size;
return size;
}
/**
* 計(jì)算字符串寬度
*
* @param height 字符串的高度
* @param font 字體大小
*
* @return 字符串的尺寸
*/
- (CGSize)widthWithHeight:(CGFloat)height andFont:(CGFloat)font {
NSDictionary *attribute = @{NSFontAttributeName: [UIFont systemFontOfSize:font]};
CGSize size = [self boundingRectWithSize:CGSizeMake(MAXFLOAT, height) options:(NSStringDrawingUsesFontLeading|NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin) attributes:attribute context:nil].size;
return size;
}
三赊抖、原因
iOS9的字體大小與之前的版本字體大小不一樣。
起碼, 在systemFont下是這樣寨典。
舉例說熏迹,字符串在 label上顯示,label的
font = [UIFont systemFontOfSize:13]
在iOS 8下凝赛,需要占用的寬度為40.f,但在iOS9下注暗,就可能需要45.f.
四、解決方法
在label初始化的時(shí)候添加如下函數(shù):
adjustsFontSizeToFitWidth
舉例如下:
- (UILabel *)priceLabel {
if (!_priceLabel) {
_priceLabel = [[UILabel alloc] init];
_priceLabel.font = H16;
_priceLabel.textColor = UIColorFromRGB(0xE71414);
_priceLabel.textAlignment = NSTextAlignmentRight;
[_priceLabel adjustsFontSizeToFitWidth];
}
return _priceLabel;
}
在布局的時(shí)候不用考慮寬度墓猎,如下:
[self.priceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
make.right.equalTo(-10);
make.centerY.equalTo(weakSelf.nameLabel);
make.height.equalTo(21);
}];