要設(shè)置label的行數(shù)為0竹习,注意一點(diǎn)小問題,就是一般情況下計算出來的高度和寬度在應(yīng)用中還是會出現(xiàn)點(diǎn)問題的[顯示偏小]列牺,只要在設(shè)置高度或者寬度的時候在actualSize的基礎(chǔ)上加上3~5像素即可
UIFont * textFont = [UIFont systemFontOfSize:36];
//最大尺寸
// MAXFLOAT 為可設(shè)置的最大高度
// 長度固定整陌,自動調(diào)整高度
CGSize size = CGSizeMake(300, MAXFLOAT);
// 高度固定,自動調(diào)整長度
CGSize size2 = CGSizeMake(MAXFLOAT,18 );
//獲取當(dāng)前那本屬性
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:textFont,NSFontAttributeName, nil];
//實(shí)際尺寸(需要自動調(diào)整什么瞎领,就取width或者h(yuǎn)eight)
CGSize actualSize = [label.text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil].size;
寫了一個函數(shù)
/** isWidth是否需要的是寬度蔓榄,length另外一邊的長度(固定的長度),text內(nèi)容默刚,fontOfSize文字大小 */
- (CGFloat)getFloatisWidth:(BOOL)isWidth fixedLength:(float)length withLabelText:(NSString *)text fontOfSize:(float)fontOfSize {
UIFont * textFont = [UIFont systemFontOfSize:fontOfSize];
// MAXFLOAT 為可設(shè)置的最大高度
CGSize size = CGSizeMake(0, 0);
if (isWidth) {
// 高度固定甥郑,自動調(diào)整長度
size = CGSizeMake(MAXFLOAT,length);
} else {
// 長度固定,自動調(diào)整高度
size = CGSizeMake(length, MAXFLOAT);
}
//獲取當(dāng)前那本屬性
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:textFont,NSFontAttributeName, nil];
//實(shí)際尺寸(需要自動調(diào)整什么荤西,就取width或者h(yuǎn)eight)
CGSize actualSize = [text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil].size;
if (isWidth) {
return actualSize.width+3;
} else {
return actualSize.height+3;
}
}