我們設置單元格高度的時候
有固定高度的情況,通過:
self.tableView.rowHeight=88;
也可以設置datasource中
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {}
實現了這個方法后,rowHeight的設置將無效。
我們平時用到的UITableView 讓其自動適應高度 我們可以
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {}
這個數據源代理方法中實現
UITableViewAutomaticDimension
這種方法 但這個方法一般情況下可以。
下面我想說一下 我經常使用的方法 就是用SDAutoLayout的布局三方
SDAutoLayout有很詳細的UITableView的各種好的方法 這里我們可義參考SDAutoLayout的官方Demo 里面有很詳細的參考代碼
這里就不重復了 github上搜索SDAutoLayout就可下載Demo
首先就是在自定義的各種單元個里 設置好各個空間的frame之后 在
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
這個方法里設置
提到這個方法 我還想多補充一句 就是曾經忽視導致遇到的坑 很久沒有解決 就是在重寫cell的時候 無法顯示子控件 然后斷點調試查看發現初始化方法沒有走
並且一直看不清 原來是寫成了- (instancetype)initWithFrame 這個方法 沒有很注意區分就這樣跳進了一個坑 而且並不會很清楚地注意到這一點
好了 言歸正傳 就是在這個方法里添加號控件之后 加一句 上代碼
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier { if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) { self.backgroundColor = [UIColor colorWithWhite:0.1 alpha:1]; [self.contentView addSubview:self.tagsView]; [self.contentView addSubview:self.editBtn]; // sd適配子控件 按鈕方法 self.editBtn.sd_layout.rightSpaceToView(self.contentView,10).centerYIs(self.tagsView.height/2).heightIs(kWidthScale(30)).widthIs(kWidthScale(30)); [self setupAutoHeightWithBottomView:self.tagsView bottomMargin:5]; } return self; }
[self setupAutoHeightWithBottomView:self.tagsView bottomMargin:5];注意是這一句
然后在viewController里面的tableView的rowHeight代理方法里面
return [self.tableV cellHeightForIndexPath:indexPath model:nil keyPath:nil cellClass:[MineOneTableViewCell class] contentViewWidth: [UIScreen mainScreen].bounds.size.width];
返回這個 model這里為nil 到時候傳遞需要的額model即可
但是 這個方法有時候會遇到問題 就是當單元格很多並且自適應cell高度 然后表格高度計算的時候 其實會有計算不出rowheight的問題 具體原因以后總結
但是最好的方法 目前找到的就是
[self.tableV cellHeightForIndexPath:indexPath cellClass:[MineOneTableViewCell class] cellContentViewWidth:kScreenWidth cellDataSetting:nil];使用這個方法來返回單元格的高度
這里可以使用注冊的方式創建cell 這樣基本無論cell也可以自適應子控件高度了 而且 tableView的rowHeight也可以完全自適應不用的自定義cell的樣式的各種高度
反正使用很多次覺得這個很好用 SDAutoLayout還提供了很多方法 慢慢總結上傳