內含動態高度文字區塊的 TableViewCell 新舊作法
舊作法(iOS7以前)
在 iOS7(含)之前,內含動態高度文字區塊(UITextView)的 UITableViewCell 的作法頗為複雜:
1. 使用 Auto Layout,將TextView四邊邊界設為0
2. 在 cellForRowAtIndexPath 裡回傳 cell
到這裡與一般程式並沒有什麼不同。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { OldDynamicCell *cell = [tableView dequeueReusableCellWithIdentifier:@"OldDynamicCell" forIndexPath:indexPath]; [cell.txtView setFont:[UIFont systemFontOfSize:15]]; [cell.txtView setText:longString]; return cell; }
3. 在heightForRowAtIndexPath裡,使用sizeThatFits來計算動態高度
為了這麼作,就必需要有一模一樣的元件來計算才會準確。因此,我們另外 alloc 了一個 Cell來作這件事:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { if(oldDynamicCellCache==nil) oldDynamicCellCache = [[OldDynamicCell alloc]init]; oldDynamicCellCache.txtView= [[UITextView alloc]init]; [oldDynamicCellCache.txtView setFont:[UIFont systemFontOfSize:15]]; [oldDynamicCellCache.txtView setText:longString]; CGSize estimateTextViewSize = [oldDynamicCellCache.txtView sizeThatFits:CGSizeMake(tableView.bounds.size.width-10, FLT_MAX)]; return estimateTextViewSize.height; }
到此程式碼即可正常運作,不過如果不希望TextView 裡的文字可以捲動的話,可以進行下個步驟。
4. 將該 TextView 的 Scrolling Enable 選項清除
因為既然我們的文字區塊已可以動態調整,而 TableView 本身也可以 scroll 了,沒必要再讓 TextView 也可以 scroll 。
iOS 8 以後的新作法
iOS 8 引進了動態 Cell 的概念,簡化了所需要的步驟。這實在是開發者的一大福因。一些小地方往往會多花了時間,整個加起來就會導致開發效率降低。反之,若每個步驟都可以節省開發與測試的時間,整個專案執行下來的速度就會加快不少。
新作法如下:
1. 使用 Auto Layout,將TextView四邊邊界設為0
2. 在 cellForRowAtIndexPath 裡回傳 cell
到這裡與一般程式並沒有什麼不同。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { NewDynamicCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NewDynamicCell" forIndexPath:indexPath]; [cell.txtView setFont:[UIFont systemFontOfSize:15]]; [cell.txtView setText:longString]; return cell; }
3. 在ViewDidLoad裡加上新的設定程式碼
self.tableView.rowHeight = UITableViewAutomaticDimension; self.tableView.estimatedRowHeight = 68.0;
4. 將該 TextView 的 Scrolling Enable 選項清除
注意:這個在新程式碼裡是必要的,否則無法運作。
5. 第五步… 沒有了,就這樣即完成了!真方便!
UITableViewAutomaticDimension 的運用不只限於 TextView,包含了其它元件在同一個 Cell 裡亦可動態調整。不過前題是 Auto Layout 必需要設好。如果 Cell 沒有照你所想的方式展開,9成9 是 Auto Layout 那裡不對。
Auto Layout 還不熟的新開發者們,好好磨練一下設的技巧吧~
堅持不使用 Auto Layout 的 Hardcore 開發者們,不要再ㄍ一ㄥ了~