//SizeForLabel.h
@interface SizeForLabel : NSObject
+(CGSize)labelRectWithSize:(CGSize)size LabelText:(NSString *)labelText Font:(UIFont *)font;
@end
//SizeForLabel.m
//參數(shù)1:Label的大小
//參數(shù)2:Label上文字內(nèi)容
//參數(shù)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字體大小(注意:要與自適應(yīng)方法里的大小一致)
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上文字內(nèi)容" Font:[UIFont systemFontOfSize:20.0f]];
//給Label設(shè)置大小
self.label.frame = CGRectMake(10, 10, [[UIScreen mainScreen]bounds].size.width - 20, digestHeight);
//文字換行
self.label.numberOfLines = 0;
圖片自適應(yīng)大小 很簡單 給圖片一個固定的寬度,讓這個圖片根據(jù)比例,適應(yīng)高度,這樣圖片不會變形
//我先把圖片設(shè)置成屏幕寬,屏幕高
UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen]bounds].size.width, [[UIScreen mainScreen]bounds].size.height)];
[self addSubview:img];
//圖片會根據(jù)寬度自適應(yīng)高度
img.contentMode = UIViewContentModeScaleAspectFit;
//圖片會根據(jù)高度自適應(yīng)寬度
//img.contentMode = UIViewContentModeScaleAspectFill;