想做一個能長高的清單,其實不用自己算行高。本文從最簡單的情況開始:Cell 裡只有一個 Label,示範如何交給系統自動決定高度,最後再幫標題加上粗體與顏色樣式。
早期想在 UITableView 裡放動態長度的內容,得實作 heightForRowAtIndexPath,自己拿字型度量去算每一行的高度,既繁瑣又容易與實際渲染不一致。自 iOS 8 導入的 Self Sizing Cells 改變了這件事:設定好之後,表格會自行量測並渲染 Cell 尺寸,開發成本大幅下降。
(1)Cell 內的檢視必須使用 Auto Layout 約束,且約束要完整。
(2)設定 tableView 的 estimatedRowHeight 初始值。
(3)把 tableView 的 rowHeight 設為 UITableViewAutomaticDimension。
三者缺一,行高就會退化回固定值。
注意 Cell 內 label 的 numberOfLines 要設為 0(預設是 1),標籤才允許換行增高。
import UIKit
class ViewController: UIViewController , UITableViewDelegate, UITableViewDataSource {
var catalog = [[String]]()
var tableView:UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// 初始化列表資料
catalog.append(["第一節:Swift 環境搭建",
"由於Swift開發環境需要在OS X系統中運行,下面就一起來學習一下swift開發環境的搭建方法。"])
catalog.append(["第二節:Swift 基本語法",
"本節介紹Swift中一些常用的關鍵字。以及引入、注釋等相關操作。"])
catalog.append(["第三節: Swift 數據類型",
"Swift 提供了非常豐富的數據類型,比如:Int、UInt、浮點數、布爾值、字符串、字符等等。"])
catalog.append(["第四節: Swift 變量",
"Swift 每個變量都指定了特定的類型,該類型決定了變量占用內存的大小。"])
catalog.append(["第五節: Swift 可選(Optionals)類型",
"Swift 的可選(Optional)類型,用於處理值缺失的情況。"])
// 建立表視圖
self.tableView = UITableView(frame: self.view.frame, style:UITableViewStyle.Plain)
self.tableView.delegate = self
self.tableView.dataSource = self
// 註冊可重複使用的單元格
self.tableView.registerClass(UITableViewCell.self,
forCellReuseIdentifier: "SwiftCell")
// 自適應行高的關鍵設定
self.tableView.estimatedRowHeight = 44.0;
self.tableView.rowHeight = UITableViewAutomaticDimension;
self.view.addSubview(self.tableView!)
}
// 只有一個分區
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1;
}
// 表格行數
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.catalog.count
}
// 建立各單元內容
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath)
-> UITableViewCell
{
// 為了效能,已建立的單元要重複使用
let identify:String = "SwiftCell"
let cell = tableView.dequeueReusableCellWithIdentifier(identify,
forIndexPath: indexPath) as UITableViewCell
// 取得對應條目
let entry = catalog[indexPath.row]
// 允許標籤自動增高
cell.textLabel?.numberOfLines = 0
cell.textLabel?.text = "\(entry[0]): \(entry[1])"
return cell
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
標題和簡介擠在同一行確實不好看。改用 textLabel 的 attributedText,就能讓標題粗體帶色、簡介另起一行以較小字型顯示,而且行高自適應照樣有效。
import UIKit
class ViewController: UIViewController , UITableViewDelegate, UITableViewDataSource {
var catalog = [[String]]()
var tableView:UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// 初始化列表資料
catalog.append(["第一節:Swift 環境搭建",
"由於Swift開發環境需要在OS X系統中運行,下面就一起來學習一下swift開發環境的搭建方法。"])
catalog.append(["第二節:Swift 基本語法",
"本節介紹Swift中一些常用的關鍵字。以及引入、注釋等相關操作。"])
catalog.append(["第三節: Swift 數據類型",
"Swift 提供了非常豐富的數據類型,比如:Int、UInt、浮點數、布爾值、字符串、字符等等。"])
catalog.append(["第四節: Swift 變量",
"Swift 每個變量都指定了特定的類型,該類型決定了變量占用內存的大小。"])
catalog.append(["第五節: Swift 可選(Optionals)類型",
"Swift 的可選(Optional)類型,用於處理值缺失的情況。"])
// 建立表視圖
self.tableView = UITableView(frame: self.view.frame, style:UITableViewStyle.Plain)
self.tableView.delegate = self
self.tableView.dataSource = self
self.tableView.registerClass(UITableViewCell.self,
forCellReuseIdentifier: "SwiftCell")
self.tableView.estimatedRowHeight = 44.0;
self.tableView.rowHeight = UITableViewAutomaticDimension;
self.view.addSubview(self.tableView!)
}
// 只有一個分區
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1;
}
// 表格行數
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.catalog.count
}
// 建立各單元內容
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath)
-> UITableViewCell
{
let identify:String = "SwiftCell"
let cell = tableView.dequeueReusableCellWithIdentifier(identify,
forIndexPath: indexPath) as UITableViewCell
let entry = catalog[indexPath.row]
// 允許標籤自動增高
cell.textLabel?.numberOfLines = 0
// 改用屬性文字,標題與簡介各自套樣式
cell.textLabel?.attributedText = getAttributedString(title: entry[0],
subtitle: entry[1])
return cell
}
// 組出帶樣式的屬性文字
func getAttributedString(title title: String, subtitle: String) -> NSAttributedString {
// 標題樣式
let titleFont = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline)
let titleColor = UIColor(red: 45/255, green: 153/255, blue: 0/255, alpha: 1)
let titleAttributes = [NSFontAttributeName: titleFont,
NSForegroundColorAttributeName: titleColor]
// 簡介樣式
let subtitleFont = UIFont.preferredFontForTextStyle(UIFontTextStyleSubheadline)
let subtitleAttributes = [NSFontAttributeName: subtitleFont]
// 拼接並回傳
let titleString = NSMutableAttributedString(string: "\(title)\n",
attributes: titleAttributes)
let subtitleString = NSAttributedString(string: subtitle,
attributes: subtitleAttributes)
titleString.appendAttributedString(subtitleString)
return titleString
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
字型這裡刻意選用 preferredFontForTextStyle 這類動態字型,會跟隨使用者在系統設定中調整的字級,對無障礙友善;代價是高度會隨字級變動,但這正好由 Self Sizing Cells 接手處理,不必另外補邏輯。
另外,這個範例把標題與簡介拼在同一個 textLabel 中。若之後需要讓兩段文字有不同行距、段落間距,或其中一段要能點擊,就該換成兩個獨立 Label 的自訂 Cell 了——那正是另一篇多 Label 自適應範例要解的問題。