iOS 计算字符串显示宽高度
2017-02-20 11:57
288 查看
ObjC(Category of NSString):
Swift(Extension of NSString):
- (CGSize)getSizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size{ CGSize resultSize = CGSizeZero; if (self.length <= 0) { return resultSize; } NSMutableParagraphStyle *style = [NSMutableParagraphStyle new]; style.lineBreakMode = NSLineBreakByWordWrapping; resultSize = [self boundingRectWithSize:CGSizeMake(floor(size.width), floor(size.height))//用相对小的 width 去计算 height / 小 heigth 算 width options:(NSStringDrawingUsesFontLeading | NSStringDrawingUsesLineFragmentOrigin) attributes:@{NSFontAttributeName: font, NSParagraphStyleAttributeName: style} context:nil].size; resultSize = CGSizeMake(floor(resultSize.width + 1), floor(resultSize.height + 1));//上面用的小 width(height) 来计算了,这里要 +1 return resultSize; }
Swift(Extension of NSString):
func getSizeWithFont(_ font:UIFont,constrainedToSize size:CGSize) -> CGSize{ if self.length == 0 { return CGSize.zero } let style = NSMutableParagraphStyle.init() style.lineBreakMode = .byWordWrapping let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin) let attributes = [NSFontAttributeName:font,NSParagraphStyleAttributeName:style] let bound = CGSize.init(width: floor(size.width), height: floor(size.height)) let rect = self.boundingRect(with: bound, options: options, attributes: attributes, context: nil) let _size = CGSize.init(width: floor(rect.width + 1), height: floor(rect.height + 1)) return _size }
相关文章推荐
- iOS小demo之根据label的宽度计算字符串显示需要的高度
- IOS 计算UILable字符串高度
- iOS 计算字符串的高度类
- 计算字符串高度 iOS
- Android下如何计算要显示的字符串所占的宽度和高度
- ios开发中计算字符串的高度
- iOS根据字符串计算UITextView高度
- Android下如何计算要显示的字符串所占的宽度和高度
- iOS 计算字符串高度
- iOS根据字符串计算UITextView高度,以及各种字符串的限定
- iOS 7 计算字符串高度
- [iOS学习]关于UILabel计算多行高度以及显示的问题
- iOS 计算label 字符串的高度
- iOS依据字符串计算UITextView高度
- Android下如何计算要显示的字符串所占的宽度和高度
- iOS根据字符串计算UITextView高度
- Android下如何计算要显示的字符串所占的宽度和高度
- iOS-计算文字(字符串)高度
- iOS计算字符串高度
- iOS根据字符串计算UITextView高度