怎样让自定义Cell的图片和文本自适应高度
Let's do it!
- 首先创建一个Model类
 - 包括一个图片名称属性
 
还有文字内容属性
#import <Foundation/Foundation.h> @interface Model : NSObject
@property (nonatomic, copy) NSString *imageName;
@property (nonatomic, copy) NSString *info;
@end
创建一个继承于UITableViewCell的MyTableViewCell,把模型作为属性,在MyTableViewCell的延展里写一个UIImageView和UILabel属性
MyTableViewCell.h #import <UIKit/UIKit.h>
@class Model;
@interface MyTableViewCell : UITableViewCell
@property (nonatomic, retain) Model *cellModel;
@end MyTableViewCell.m #import "MyTableViewCell.h"
#import "Model.h"
@interface MyTableViewCell () @property (nonatomic, retain) UIImageView *myImageView;
@property (nonatomic, retain) UILabel *myLabel;
@end
@implementation MyTableViewCell
- (void)dealloc {
[_cellModel release];
[_myImageView release];
[_myLabel release];
[super dealloc];
}
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]; self.myImageView = [[UIImageView alloc] initWithFrame:CGRectZero];
[self.contentView addSubview:_myImageView];
[_myImageView release]; self.myLabel = [[UILabel alloc] initWithFrame:CGRectZero];
_myLabel.numberOfLines = ;
[self.contentView addSubview:_myLabel];
[_myLabel release]; return self;
} # pragma mark - override setter
- (void)setCellModel:(Model *)cellModel {
if (_cellModel != cellModel) {
[_cellModel release];
_cellModel = [cellModel retain];
_myImageView.image = [UIImage imageNamed:cellModel.imageName];
_myLabel.text = cellModel.info;
}
} - (void)layoutSubviews {
[super layoutSubviews];
// 首先拿到图片的原尺寸
CGSize size = _myImageView.image.size;
// 用固定的宽度除以图片原宽,得到一个比例
CGFloat scale = self.contentView.frame.size.width / size.width;
// 根据比例求得固定的高度
CGFloat realHeight = size.height * scale;
// 最后设置imageView的frame
_myImageView.frame = CGRectMake(, , self.contentView.frame.size.width, realHeight);
// label的y坐标根据imageView的大小来决定,所以一定写在imageView高度计算之后
_myLabel.frame = CGRectMake(, _myImageView.frame.origin.y + _myImageView.frame.size.height, _myImageView.frame.size.width, );
// sizeToFit根据宽度算高度,所以一定要先有一个宽度(注意label显示行数需要设置为0)
[_myLabel sizeToFit];
}
@end
#import "RootViewController.h"
#import "Model.h"
#import "MyTableViewCell.h" static NSString *const reusableIndentifier = @"cell"; @interface RootViewController ()
<
UITableViewDelegate,
UITableViewDataSource
> @property (nonatomic, retain) NSArray *array; @end @implementation RootViewController - (void)viewDidLoad {
[super viewDidLoad]; Model *model = [[Model alloc] init];
model.imageName = @"Dog4.jpg";
model.info = @"Swift is a powerful and intuitive programming language for macOS, iOS, watchOS and tvOS. Writing Swift code is interactive and fun, the syntax is concise yet expressive, and Swift includes modern features developers love. Swift code is safe by design, yet also produces software that runs lightning-fast. Swift 3 is a thorough refinement of the language and the API conventions for the frameworks you use every day. These improvements make the code you write even more natural, while ensuring your code is much more consistent moving forward. For example, select Foundation types such as the new Date type are easier to use and are much faster than previous releases, and the Calendar type uses enums to feel more at home within Swift. SwiftSwiftSwiftSwiftSwiftSwiftSwift"; self.array = @[model]; UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
tableView.backgroundColor = [UIColor cyanColor];
tableView.delegate = self;
tableView.dataSource = self;
[self.view addSubview:tableView];
[tableView release]; }
# pragma mark - 代理方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return _array.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
MyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reusableIndentifier];
if (nil == cell) {
cell = [[MyTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reusableIndentifier];
}
cell.cellModel = _array[indexPath.row];
return cell;
} # pragma mark - 设置高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
Model *model = _array[indexPath.row];
UIImage *image = [UIImage imageNamed:model.imageName];
CGSize size = image.size;
CGFloat scale = tableView.bounds.size.width / size.width;
CGFloat realHeight = size.height * scale; // label自适应高度
// 首先定义一个字符变量接收模型里的info属性值
NSString *info = model.info;
// 宽度要和label宽度一样
CGSize infoSize = CGSizeMake(tableView.frame.size.width, );
NSDictionary *dic = @{NSFontAttributeName : [UIFont systemFontOfSize:.f]};
// 计算文字高度
// 参数1:自适应尺寸,提供一个宽度,去适应高度
// 参数2:自适应设置(以行为矩形区域自适应,以字体字形自适应)
// 参数3:文字属性,通常这里面需要知道的是字体大小
// 参数4:绘制文本上下文,做底层排版时使用,填nil即可
CGRect infoRect = [info boundingRectWithSize:infoSize options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
// 图片高度 + 文字高度
// 上面方法在计算文字高度的时候可能得到的是带小数的值,如果用来做视图尺寸的适应的话,需要使用更大一点的整数值
// 取整的方法使用ceil函数
return realHeight + ceil(infoRect.size.height); }
@end
怎样让自定义Cell的图片和文本自适应高度的更多相关文章
- web图片100%宽度自适应,高度不塌陷
		
一般在web端图片100%自适应,在页面加载的时候存在高度塌陷的问题 解决这个问题其实很简单,用padding-top设置百分比值来实现自适应,公式如下 padding-top = (Image He ...
 - iOS学习之UI自定义cell
		
一.自定义Cell 为什么需要自定义cell:系统提供的cell满足不了复杂的样式,因此:自定义Cell和自定义视图一样,自己创建一种符合我们需求的Cell并使用这个Cell.如下图所示的这些Cell ...
 - IOS Swift语言开发 tableView的重用以及自cell的自适应高度
		
http://www.aichengxu.com/iOS/11143168.htm 一.准备数据 (这是一个元组,第一个元素为英雄的名字;第二个元素为英雄头像图片的名字,格式为.PNG,如果为其他的格 ...
 - 【原】文本图片自适应高度小bug以及解决办法
		
自定义cell的文本图片自适应高度代码,如果存在自定义的cell赋值封装,就必须将自适应高度代码写在这个方法中
 - 文本图片自适应高度小bug以及解决办法
		
自定义cell的文本图片自适应高度代码,如果存在自定义的cell赋值封装,就必须将自适应高度代码写在这个方法中 点击效果: 注:- (void)layoutSubviews 方法不能同时操作,否则会出 ...
 - Cell自适应高度及自定义cell混合使…
		
第一部分:UItableViewCellAdaptionForHeight : cell的自适应高度 第二部分:CustomTableViewCell:自定义cell的混合使用(以简单通讯录为例) = ...
 - 自定义cell自适应高度
		
UITableView在许多App种被大量的应用着,呈现出现的效果也是多种多样的,不能局限于系统的一种样式,所以需要自定义cell 自定义cell呈现的内容也是多种多样的,内容有多有少,所以需要一种能 ...
 - iOS开发小技巧--纯代码自定义cell
		
纯代码自定义cell 自定义cell的步骤(每个cell的高度不一样,每个cell里面显示的内容也不一样) 1.新建一个继承自UITableViewCell的子类 2.在initWithStyle:方 ...
 - 自定义cell的一些知识
		
1.要往cell里面添加一个自定义的子控件,都是添加到cell的contentView,不是添加到cell里面. 2.通过xib自定义cell * 添加tableView * 加载团购数据 * 新建x ...
 
随机推荐
- Mapreduce实战:序列化与反序列化 int,int[],string[][]
			
最新一期<中国IT产业发展报告>在2016中国(深圳)IT领袖峰会上正式发布,数字中国联合会常务理事李颖称.中国IT产业完毕了从要素驱动向效率驱动的过渡,眼下正在由效率驱动向创新驱动发展. ...
 - Basic Socket
			
http://www.avajava.com/tutorials/lessons/how-do-i-make-a-socket-connection-to-a-server.html?page=1 t ...
 - ffmpeg下载rtmp flv
			
ffmpeg -i rtmp://shanghai.chinatax.gov.cn:1935/fmsApp/16a0148f117.flv -c copy dump.flv
 - 使用Entity Framework和WCF Ria Services开发SilverLight之6:查找指定字段
			
对数据库表指定字段的查找,又是实际工作中的一项必要工作.SL客户端仅获取实际需要的指定的字段,好处很多,比如:有助于减少网络流量. 有两类这样的使用场景. 1:联表查询不需要外键表 在上一篇中,我们使 ...
 - IOS8 通知中心(Notification Center)新特性
			
本文转载至 http://blog.csdn.net/jinkaiouyang/article/details/30029441 ios手机apple通知中心notificationCenter ...
 - 【BZOJ3837】[Pa2013]Filary 随机化神题
			
[BZOJ3837][Pa2013]Filary Description 给定n个正整数,从中挑出k个数,满足:存在某一个m(m>=2),使得这k个数模m的余数相等. 求出k的最大值,并求出此时 ...
 - 开源G711(PCMA、PCMU)/G726转AAC项目EasyAACEncoder
			
EasyDarwin开源社区整理了一份G711(PCMA.PCMU)/G726转AAC的转码库,支持Windows/Linux跨平台使用,将安防标准的G711转成移动互联网常用的AAC格式,希望能给大 ...
 - Node 文件上传,ZIP
			
上传文件: 很多人会使用第三包进行文件的上传,例如formidable. 我也研究过,可是与Express3.x框架一起使用时,发现上传的文件总是找不到.结果原因是下面这句导致: app.use(ex ...
 - NSDate的具体使用(转载)
			
NSDate的具体使用 时间与日期处理 主要有以下类: NSDate -- 表示一个绝对的时间点 NSTimeZone -- 时区信息 NSLocale -- 本地化信息 NSDateComponen ...
 - POJ2478 Farey Sequence —— 欧拉函数
			
题目链接:https://vjudge.net/problem/POJ-2478 Farey Sequence Time Limit: 1000MS Memory Limit: 65536K To ...