//SizeForLabel.h
@interface SizeForLabel : NSObject
+(CGSize)labelRectWithSize:(CGSize)size LabelText:(NSString *)labelText Font:(UIFont *)font;
@end
//SizeForLabel.m
//参数1:Label的大小
//参数2:Label上文字内容
//参数3:文字的字体大小
+(CGSize)labelRectWithSize:(CGSize)size LabelText:(NSString *)labelText Font:(UIFont *)font{
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName, nil];
CGSize actualsize = [labelText boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil].size; return actualsize;
}
self.label = [[UILabel alloc] init];
//Label字体大小(注意:要与自适应方法里的大小一致)
self.label.font = [UIFont systemFontOfSize:20.0f];[self addSubview:self.label];
//计算大小(我这里算的是固定宽度,计算高度;也可以固定宽度,计算高度)
CGSize digestHeight = [SizeForLabel labelRectWithSize:CGSizeMake([[UIScreen mainScreen]bounds].size.width - 20, MAXFLOAT) LabelText:@"Label上文字内容" Font:[UIFont systemFontOfSize:20.0f]];
//给Label设置大小
self.label.frame = CGRectMake(10, 10, [[UIScreen mainScreen]bounds].size.width - 20, digestHeight);
//文字换行
self.label.numberOfLines = 0;
图片自适应大小 很简单 给图片一个固定的宽度,让这个图片根据比例,适应高度,这样图片不会变形
//我先把图片设置成屏幕宽,屏幕高
UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen]bounds].size.width, [[UIScreen mainScreen]bounds].size.height)];
[self addSubview:img];
//图片会根据宽度自适应高度
img.contentMode = UIViewContentModeScaleAspectFit;
//图片会根据高度自适应宽度
//img.contentMode = UIViewContentModeScaleAspectFill;