在讨论表格视图之前,让我们讨论一下adjustsFontForContentSizeCategory。这样做的目的是控件会自动为我们调整字体。在此之前,您必须手动为UIContentSizeCategory.didChangeNotification(以前称为UIContentSizeCategoryDidChangeNotification)添加观察者。
因此,例如,在 Swift 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: UIContentSizeCategory.didChangeNotification, object: nil, queue: .main) { [weak self] notification in
self?.dynamicTextLabel.font = .preferredFont(forTextStyle: .body)
}
}
deinit {
NotificationCenter.default.removeObserver(self, name: UIContentSizeCategory.didChangeNotification, 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
}
}
好的,话虽如此,表视图会自动观察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
}