在討論表格視圖之前,我們來討論一下adjustsFontForContentSizeCategory
。這樣做的目的是控件會自動爲我們調整字體。在此之前,您必須手動添加UIContentSizeCategoryDidChangeNotification
的觀察者。
因此,例如,在斯威夫特3,在IOS版本之前的10,爲了當用戶改變了他們的首選字體大小有字體更新,我們不得不這樣做:
class ViewController: UIViewController {
@IBOutlet weak var dynamicTextLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
dynamicTextLabel.font = .preferredFont(forTextStyle: .body)
NotificationCenter.default.addObserver(forName: .UIContentSizeCategoryDidChange, object: nil, queue: .main) { [weak self] notification in
self?.dynamicTextLabel.font = .preferredFont(forTextStyle: .body)
}
}
deinit {
NotificationCenter.default.removeObserver(self, name: .UIContentSizeCategoryDidChange, object: nil)
}
}
在iOS系統中10,我們可以使用adjustsFontForContentSizeCategory
並且不再需要觀察者,簡化了上面:
class ViewController: UIViewController {
@IBOutlet weak var dynamicTextLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
dynamicTextLabel.font = .preferredFont(forTextStyle: .body)
dynamicTextLabel.adjustsFontForContentSizeCategory = true
}
}
OK,話雖如此,表視圖觀察UIContentSizeCategoryDidChangeNotification
自動。無論您看到文本大小調整是否是在單元格標籤上使用動態類型的產物。如果使用動態文本,像下面,你將看到表更新作爲系統的首選字體大小的變化(不使用adjustsFontForContentSizeCategory
):
class ViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// make sure the cell resizes for the font with the following two lines
tableView.estimatedRowHeight = 44
tableView.rowHeight = UITableViewAutomaticDimension
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1000
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.font = .preferredFont(forTextStyle: .body)
// cell.textLabel?.adjustsFontForContentSizeCategory = true
cell.textLabel?.text = "Row \(indexPath.row)"
return cell
}
}
正如你所看到的,我所要做的就是設置的唯一的事字體轉換爲動態文本,並自動更新表格。根據我的經驗,在表格視圖中,不需要adjustsFontForContentSizeCategory
(它看起來像表格視圖必須自己觀察必要的通知),但是如果您沒有遇到自動調整大小的行爲,您可以隨時對其進行設置。
如果明確不希望表格視圖單元格的標籤的字體改變,那麼就不要使用動態文本,例如:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.font = .systemFont(ofSize: 17)
cell.textLabel?.text = "Row \(indexPath.row)"
return cell
}
來源
2017-03-23 07:00:07
Rob