寫法一:對象方法,傳入:字體/最大尺寸. 便可獲得寬高,
最大尺寸主要限制寬度,若是是一行就給個{MAXFLOAT,MAXFLOAT};若是是多行就限制X值,Y值隨便給字體
- (CGSize)sizeWithFont:(UIFont *)font maxSize:(CGSize)maxSize { NSDictionary *attrs = @{NSFontAttributeName : font}; return [self boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size; }
寫法二: 傳入文字/字體/最大尺寸. 便可獲得該文字寬高對象
-(CGSize)sizeWithText:(NSString *)text font:(UIFont *)font maxW:(CGFloat)maxW { NSMutableDictionary *attrs=[NSMutableDictionary dictionary]; attrs[NSFontAttributeName]=font; CGSize maxSize=CGSizeMake(maxW, MAXFLOAT); return [text boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size; } - (CGSize)sizeWithText:(NSString *)text font:(UIFont *)font { return [self sizeWithText:text font:font maxW:MAXFLOAT]; }
自定義控件設置UILable的位置:blog
self.nameLabel.frame=CGRectMake(iconX, iconY, iconWH, iconWH);it
或者:io
CGFloat timeX = nameX; CGFloat timeY = CGRectGetMaxY(self.nameLabelF) + HWStatusCellBorderW; CGSize timeSize = [self sizeWithText:status.created_at font:HWStatusCellTimeFont]; self.timeLabelF = (CGRect){{timeX, timeY}, timeSize};