带填充间距的 UILabel 在项目中的使用
效果
实现方式:
1、自定义上文中的 SOInsetsLabel
2、在自定义 View 中初始化 label
// // PTDiscoverDetailHeader.m // kidsPlay // // Created by LiLiLiu on 15/9/13. // Copyright (c) 2015年 LiLiLiu. All rights reserved. // #import "PTDiscoverDetailHeader.h" #import "PTOperateItem.h" #import "SOInsetsLabel.h" #import "Util.h" #define HEADERVIEW_MARGIN 10 static CGFloat const lblIndent = 16.0f; static UIEdgeInsets titleLblInsets = {.top = lblIndent, .left = lblIndent, .bottom = lblIndent, .right = lblIndent}; static UIEdgeInsets descLblInsets = {.top = 0, .left = lblIndent, .bottom = lblIndent, .right = lblIndent}; static CGFloat const PTDiscoverDetailHeaderImageHeight = 235.0f; #define TOPIC_TITLE_FONT [UIFont fontWithName:TextName size:18] @interface PTDiscoverDetailHeader () @property (strong, nonatomic) SOInsetsLabel *topicTitleLbl; @end @implementation PTDiscoverDetailHeader - (void)dealloc { SORELEASE(_item); SOSUPERDEALLOC(); } - (instancetype)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if(self) { [self addSubview:self.topicTitleLbl]; } return (self); } - (void)layoutSubviews { [super layoutSubviews]; CGSize size = self.bounds.size; self.topicTitleLbl.text = self.item.title; self.topicDescLbl.text = self.item.note; //文字高度 CGFloat titleHeight = [Util lableWithTextStringHeight:self.item.title andTextFont:TOPIC_TITLE_FONT andLableWidth:size.width-lblIndent*2]; // // CGSize titleSize = [self.item.title boundingRectWithSize:CGSizeMake(size.width-lblIndent*2, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:TOPIC_TITLE_FONT} context:nil].size; self.topicTitleLbl.frame = CGRectMake(0, 0, size.width, titleHeight); }else{ self.topicTitleLbl.frame = CGRectMake(0, 0, size.width, 0); } } #pragma mark - getter - (SOInsetsLabel *)topicTitleLbl{ if (!_topicTitleLbl) { _topicTitleLbl = [[SOInsetsLabel alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.bounds), 20) andInsets:titleLblInsets]; _topicTitleLbl.backgroundColor = [UIColor whiteColor]; _topicTitleLbl.numberOfLines = 0; _topicTitleLbl.lineBreakMode = NSLineBreakByWordWrapping; _topicTitleLbl.font = TOPIC_TITLE_FONT; _topicTitleLbl.textColor = [UIColor blackColor]; _topicTitleLbl.textAlignment = NSTextAlignmentLeft; } return _topicTitleLbl; } @end
3、Util 类中根据文字大小和宽度计算高度的类方法
//根据文字的大小和既定的宽度,来计算文字所占的高度 +(CGFloat) lableWithTextStringHeight:(NSString*)labelString andTextFont:(UIFont*)font andLableWidth:(float)width { if (labelString == nil) { return 0.0; } NSDictionary *dic = @{NSFontAttributeName: font}; return [labelString boundingRectWithSize:CGSizeMake(width, 100000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic // 文字的属性 context:nil].size.height; }