iOS7之前计算字符串长宽的方法是:
- (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size lineBreakMode:
(NSLineBreakMode)lineBreakMode NS_DEPRECATED_IOS(2_0, 7_0, "Use -
boundingRectWithSize:options:attributes:context:") __TVOS_PROHIBITED; // NSTextAlignment is
not needed to determine size
不过在iOS7之后就过时了,有新的方法替换它。
下面是把iOS7的新方法封装成UILabel的类目以方便实用:
头文件:
//
// NSString+FrameSize.h
// Xcode7Test
//
// Created by 于建祥 on 16/9/13.
// Copyright © 2016年 于建祥. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface NSString (FrameSize)
- (CGSize)boundingRectWithSize:(CGSize)size andFont:(UIFont *)font;
@end
实现文件:
//
// NSString+FrameSize.m
// Xcode7Test
//
// Created by 于建祥 on 16/9/13.
// Copyright © 2016年 于建祥. All rights reserved.
//
#import "NSString+FrameSize.h"
@implementation NSString (FrameSize)
- (CGSize)boundingRectWithSize:(CGSize)size andFont:(UIFont *)font
{
NSDictionary *attribute = @{NSFontAttributeName:font};
CGSize retSize = [self boundingRectWithSize:size
options:\
NSStringDrawingTruncatesLastVisibleLine |
NSStringDrawingUsesLineFragmentOrigin |
NSStringDrawingUsesFontLeading
attributes:attribute
context:nil].size;
return retSize;
}
@end
使用时:
CGSize strSize = [str boundingRectWithSize:CGSizeMake(200, NSIntegerMax) andFont:[UIFont systemFontOfSize:14]];
label.frame = CGRectMake(10, 20, strSize.width , strSize.height);
网友评论