1,效果圖
儲存格內有兩個文字標籤,分別顯示標題和內容簡介。同時兩個標籤都是自增長的。
2,StoryBoard設定
(1)將儲存格 cell 的 identifier 設定成“myCell”
(2)從物件程式庫中拖入2個 Label 控制項到 cell 中,分別用於顯示標題和內容。
(3)並在 Attributes 面板中將兩個 Label 的 Tag 值分別設定為 1 和 2,供代碼中擷取標籤。
(4)最後為了讓兩個 Label 標籤能自動成長,將其 Lines 屬性設定為 0。
3,約束設定
除了儲存格 Cell 需要使用 Auto Layout 約束,儲存格內的標籤也要設定正確的約束,否則無法實現 Self Sizing Cells。
(1)第一個 Label(用於顯示標題)設定上下左右 4 個約束。
(2)第二個 Label(用於顯示內容簡介)設定左右下 3 個約束。
例子
import UIKit
class ViewController: UIViewController , UITableViewDelegate, UITableViewDataSource {
var catalog = [[String]]()
@IBOutlet weak 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.delegate = self
self.tableView.dataSource = self
//設定estimatedRowHeight屬性預設值
self.tableView.estimatedRowHeight = 44.0;
//rowHeight屬性設定為UITableViewAutomaticDimension
self.tableView.rowHeight = UITableViewAutomaticDimension;
}
//在本例中,只有一個分區
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1;
}
//返回表格行數(也就是返回控制項數)
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.catalog.count
}
//建立各單元顯示內容(建立參數indexPath指定的單元)
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath)
-> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("myCell",
forIndexPath: indexPath) as UITableViewCell
//擷取對應的條目內容
let entry = catalog[indexPath.row]
let titleLabel = cell.viewWithTag(1) as! UILabel
let subtitleLabel = cell.viewWithTag(2) as! UILabel
titleLabel.text = entry[0]
subtitleLabel.text = entry[1]
return cell
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}