1、問題起源:
做了幾個詳情頁,都是需要用到滾動視圖來滾動,但是滾動視圖的計算滾動范圍高度,所以獲得計算滾動視圖內(nèi)所有控件的高度,最讓我困惑的是計算UIlabel的高度。
2、解決問題描述:
1)有問題的解決方案:
使用一個UIlabel的分類,把字體和行間距傳到分類的方法,計算的高度不夠精準(zhǔn)。最大問題是第四行的時候內(nèi)容顯示不完整,會以省略號結(jié)尾;還有當(dāng)顯示很多行時上下邊距會變得越來越大。
2)完美的解決方案(直接看代碼)
由于UIlabel沒有改變邊距的屬性,所以只能自定義UIlabel
#import@interface CustomLabel : UILabel
@property (nonatomic, assign) UIEdgeInsets textInsets; // 控制字體與控件邊界的間隙
@end
#import "CustomLabel.h"
@implementation CustomLabel
- (instancetype)init {
if (self = [super init]) {
_textInsets = UIEdgeInsetsZero;
}
return self;
}
- (instancetype)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
_textInsets = UIEdgeInsetsZero;
}
return self;
}
- (void)drawTextInRect:(CGRect)rect {
[super drawTextInRect:UIEdgeInsetsInsetRect(rect, _textInsets)];
}
使用代碼
//定義對象
@property(nonatomic,strong) CustomLabel *summaryLabel;
//初始化UIlabel
self.summaryLabel = [[CustomLabel alloc] initWithFrame:CGRectZero];
self.summaryLabel.text = @"還是覅順豐快遞是否健康的時間反饋都是房價肯定是連接克魯塞德九分褲哈哈回復(fù)哈回復(fù)哈哈撒哈哈哈哈哈快放假熬枯受淡艱苦奮斗時間反饋來的時間";
//設(shè)置上下邊距
self.summaryLabel.textInsets = UIEdgeInsetsMake(-20*SCALE_FIT, 0, -20*SCALE_FIT, 0);
self.summaryLabel.numberOfLines = 0;
self.summaryLabel.textColor = GLOBAL_GRAY_COLOR;
self.summaryLabel.font = FONT(asp_fitScreen(26));
[_bottomView addSubview:self.summaryLabel];
//計算UIlabel的高度
weakSelf.summaryLabel.font = FONT(asp_fitScreen(26));
CGFloat labelWidth = SCREEN_WIDTH - 80*SCALE_FIT;
NSLog(@"-----------width %f",80*SCALE_FIT);
NSDictionary *attrs = @{NSFontAttributeName:weakSelf.summaryLabel.font};
CGSize maxSize = CGSizeMake(labelWidth, MAXFLOAT);
CGSize size = [weakSelf.summaryLabel.text boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size;
weakSelf.summaryLabel.pz_viewSize = size;