//定义宏:
#define kFontSize 14
#define kPhotoCell_Width 300
#define kPhotoCell_MarginBetween 3
#define kPhotoCell_TitleLabel_Height 25
//方法:
+ (CGFloat)heightForRowWithModel:(PhotoInfo *)photoInfo
{
//1.图片的高度(让图片等比例缩放)
//1.1获取图片
UIImage *image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"TSummer" ofType:@"png"]];
//1.2计算图片的高度
CGFloat imageHeight = [self heightForImage:image];
//2.文本的高度
CGFloat textHeight = [self heightForText:photoInfo.introduction];
//3.返回cell 的总高度
return kPhotoCell_TitleLabel_Height + imageHeight + textHeight + 4 * kPhotoCell_MarginBetween;
}
//单独计算图片的高度
+ (CGFloat)heightForImage:(UIImage *)image
{
//(1)获取图片的大小
CGSize size = image.size;
//(2)求出缩放比例
CGFloat scale = kPhotoCell_Width / size.width;
CGFloat imageHeight = size.height * scale;
return imageHeight;
}
//单独计算文本的高度
+ (CGFloat)heightForText:(NSString *)text
{
//设置计算文本时字体的大小,以什么标准来计算
NSDictionary *attrbute = @{NSFontAttributeName:[UIFont systemFontOfSize:kFontSize]};
return [text boundingRectWithSize:CGSizeMake(kPhotoCell_Width, 1000) options:(NSStringDrawingUsesFontLeading | NSStringDrawingUsesLineFragmentOrigin) attributes:attrbute context:nil].size.height;
}
本文详细介绍了如何使用Objective-C计算iOS应用中单行文本和图片的高度,并以此为基础计算整个PhotoInfo对象所占的总高度。通过自定义的方法,实现了对不同元素尺寸的精确控制,为开发者提供了高效、灵活的界面布局解决方案。
2274

被折叠的 条评论
为什么被折叠?



