前言
首先我們需要明白為什么要讓Cell里的圖片或者文本自適應高度,因為很多時候Cell中的數(shù)據(jù)是通過網(wǎng)絡請求得來的,我們在自定義Cell的時候并不能把Cel的高度給一個死值,否則會出現(xiàn)圖片被壓縮或者文字顯示不全的情況。這個時候我們就要動態(tài)設置Cell的高度。
Let's do it!
- 首先創(chuàng)建一個Model類
- 包括一個圖片名稱屬性
- 還有文字內容屬性
#import <Foundation/Foundation.h>
@interface Model : NSObject
@property (nonatomic, copy) NSString *imageName;
@property (nonatomic, copy) NSString *info;
@end
- 自定義Cell
- 創(chuàng)建一個繼承于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 = 0;
[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;
// 根據(jù)比例求得固定的高度
CGFloat realHeight = size.height * scale;
// 最后設置imageView的frame
_myImageView.frame = CGRectMake(0, 0, self.contentView.frame.size.width, realHeight);
// label的y坐標根據(jù)imageView的大小來決定,所以一定寫在imageView高度計算之后
_myLabel.frame = CGRectMake(0, _myImageView.frame.origin.y + _myImageView.frame.size.height, _myImageView.frame.size.width, 40);
// sizeToFit根據(jù)寬度算高度,所以一定要先有一個寬度(注意label顯示行數(shù)需要設置為0)
[_myLabel sizeToFit];
}
@end
- 在根視圖控制器里創(chuàng)建一個tableView
#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, 1000);
NSDictionary *dic = @{NSFontAttributeName : [UIFont systemFontOfSize:17.f]};
// 計算文字高度
// 參數(shù)1:自適應尺寸,提供一個寬度,去適應高度
// 參數(shù)2:自適應設置(以行為矩形區(qū)域自適應,以字體字形自適應)
// 參數(shù)3:文字屬性,通常這里面需要知道的是字體大小
// 參數(shù)4:繪制文本上下文,做底層排版時使用,填nil即可
CGRect infoRect = [info boundingRectWithSize:infoSize options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
// 圖片高度 + 文字高度
// 上面方法在計算文字高度的時候可能得到的是帶小數(shù)的值,如果用來做視圖尺寸的適應的話,需要使用更大一點的整數(shù)值
// 取整的方法使用ceil函數(shù)
return realHeight + ceil(infoRect.size.height);
}
@end
文本自適應高度:根據(jù)文本內容設定Label高度
- 關鍵代碼
// label自適應高度
// 首先定義一個字符變量接收模型里的info屬性值
NSString *info = model.info;
// 寬度要和label寬度一樣
CGSize infoSize = CGSizeMake(tableView.frame.size.width, 1000);
NSDictionary *dic = @{NSFontAttributeName : [UIFont systemFontOfSize:17.f]};
// 計算文字高度
// 參數(shù)1:自適應尺寸,提供一個寬度,去適應高度
// 參數(shù)2:自適應設置(以行為矩形區(qū)域自適應,以字體字形自適應)
// 參數(shù)3:文字屬性,通常這里面需要知道的是字體大小
// 參數(shù)4:繪制文本上下文,做底層排版時使用,填nil即可
CGRect infoRect = [info boundingRectWithSize:infoSize options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
- 效果圖
- 根據(jù)文字的多少動態(tài)改變cell的高度


圖片自適應高度:根據(jù)圖片寬度進行的等比例縮放
- 關鍵代碼
- 注意:
- 圖片自適應高度的代碼要在layoutSubview方法還有tableView:heightForRowAtIndexPath:方法中各寫一遍
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;
- 效果圖
- 更改定寬后的效果
- 圖片高度也按照比例縮小了

最后
TableView作為iOS開發(fā)中最重要的核心控件,幾乎在市面上所有的APP中都能看到它的身影,所以學會熟練使用它非常有必要。