1,儲存格高度自適應
有時我們使用表格(UITableView)顯示列表資料。不希望每個儲存格的高度是固定的,最好能根據儲存格中的內容來自適應高度。在過去,我們如果想在表格視圖中展示可變高度的動態內容,需要手動計算行高,比較麻煩。
自 iOS8 起,UITableView 加入了一項新功能:Self Sizing Cells。設定後表格會自動計算儲存格的尺寸並渲染,大大節省了開發時間。
2,使用Self Sizing Cells的條件
(1)儲存格 Cell 需要使用 Auto Layout 約束。
(2)需要指定 tableView 的 estimatedRowHeight 屬性預設值。
(2)將 tableView 的 rowHeight 屬性設定為 UITableViewAutomaticDimension。
3,範例效果圖
下面先通過一個最簡單的範例示範如何使用 Self Sizing Cells。儲存格就是最原始的 UITableViewCell,即裡面只有一個文
4,範例代碼
這裡注意我們要將儲存格 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")
//設定estimatedRowHeight屬性預設值
self.tableView.estimatedRowHeight = 44.0;
//rowHeight屬性設定為UITableViewAutomaticDimension
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
}
//建立各單元顯示內容(建立參數indexPath指定的單元)
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()
}
}
5,功能改進
前面範例中,每區段標頭和內容簡介都放一起不太美觀。下面通過 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")
//設定estimatedRowHeight屬性預設值
self.tableView.estimatedRowHeight = 44.0;
//rowHeight屬性設定為UITableViewAutomaticDimension
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
}
//建立各單元顯示內容(建立參數indexPath指定的單元)
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()
}
}