https://lvwenhan.com/ios/449.html
#import "ViewController.h"
#import "MyTableViewCell.h"
static NSString *cellIdentifier = @"mycell"; @interface ViewController () <UITableViewDelegate, UITableViewDataSource>
@property (strong, nonatomic) NSArray *listArr;
@property (strong, nonatomic) MyTableViewCell *cell;
@end @implementation ViewController
@synthesize listArr; - (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self.tableView registerNib:[UINib nibWithNibName:@"MyTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:cellIdentifier];
self.tableView.estimatedRowHeight = ;//很重要保障滑动流畅性
self.cell = [self.tableView dequeueReusableCellWithIdentifier:cellIdentifier]; self.listArr = @[@"Do any additional setup after loading the view, typically from a nib.",
@"test",
@"UITableViewCell 高度自适应一直是我们做动态Cell高度时遇到的最烦躁的问题,Cell动态高度计算可以去看看 sunny 的这篇文章介绍,今天主要和大家分享下我在使用 systemLayoutSizeFittingSize 系统自带方法计算高度的一些心得!"];
} - (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
} - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return ;
} - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return listArr.count;
} - (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
MyTableViewCell *cell = self.cell;
cell.myLabel.text = listArr[indexPath.row];
cell.contentView.translatesAutoresizingMaskIntoConstraints = NO;
CGFloat fittingHeight = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
return fittingHeight;
} - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
self.cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; if (self.cell == nil) {
UINib *nib = [UINib nibWithNibName:@"MyTableViewCell" bundle:nil];
[tableView registerNib:nib forCellReuseIdentifier:cellIdentifier];
self.cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
}
self.cell.myLabel.backgroundColor = [UIColor blueColor];
self.cell.myLabel.textColor = [UIColor whiteColor];
self.cell.myLabel.text = [listArr objectAtIndex:indexPath.row];
return self.cell;
} @end