UIIabel自适配高度
可以选择写一个继承自NSString的Category。然后添加一个方法:
- (CGSize)sizeWithFont:(UIFont *)font andSize:(CGSize)cSize;
方法里的实现如下:
- (CGSize)sizeWithFont:(UIFont *)font andSize:(CGSize)cSize{
CGSize size=CGSizeZero;
#ifdef __IPHONE_7_0
if (IOS7) { // #define IOS7 [[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0
NSDictionary* attributes = [NSDictionary dictionaryWithObjectsAndKeys: font, NSFontAttributeName, nil];
CGRect rect = [self boundingRectWithSize:cSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil];
size = rect.size;
}else{
size = [self sizeWithFont:font constrainedToSize:cSize];
}
#else
size = [self sizeWithFont:font constrainedToSize:cSize];
#endif
return size;
}
最后,在需要用到的类里,添加 #import "NSString+SizeFont.h" 引用,
最最后使用:
eg: UILable *lblContent = [[UILabel alloc]init];
lblContent.text = strContent;
CGFloat height = [strContent sizeWithFont:[UIFont systemFontOfSize:18.0f] andSize:CGSizeMake(SCREEN_WIDTH-30, MAXFLOAT)].height; //#define SCREEN_WIDTH [[UIScreen mainScreen] bounds].size.width
这个height就是lblContent的变化高度。最后把lblContent的frame设置一下就行了。
lblContent.frame = (CGRect){lblContent.frame.origin,SCREEN_WIDTH-30,height};
不出意外应该就OK了。嘿嘿~~