iOS UIlabel計算高度(上下邊距問題)

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;

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容