use*_*883 7 fonts accessibility ios dynamic-type-feature
我在标准UITableViewCell的textLabel上设置adjustsFontForContentSizeCategory.当我转到"设置","常规","辅助功能","更大文本"来更改字体大小然后再返回到我的应用程序时,UITableViewCell的UILabel会相应地进行更改.这应该不会发生,是吗?
adjustsFontForContentSizeCategory的目的究竟是什么?如何防止UITableViewCells标签更改其字体大小?
在我们进入表格视图之前,让我们讨论一下adjustsFontForContentSizeCategory.这样做的目的是控件将自动调整我们的字体.在此之前,您必须手动添加观察者UIContentSizeCategoryDidChangeNotification.
因此,例如,在Swift 3中,在10之前的iOS版本中,为了在用户更改其首选字体大小时进行字体更新,我们必须执行以下操作:
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)
}
}
Run Code Online (Sandbox Code Playgroud)
在iOS 10中,我们可以使用adjustsFontForContentSizeCategory并且不再需要观察者,将上述内容简化为:
class ViewController: UIViewController {
@IBOutlet weak var dynamicTextLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
dynamicTextLabel.font = .preferredFont(forTextStyle: .body)
dynamicTextLabel.adjustsFontForContentSizeCategory = true
}
}
Run Code Online (Sandbox Code Playgroud)
好的,据说,表视图会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
}
}
Run Code Online (Sandbox Code Playgroud)
如您所见,我唯一要做的就是将字体设置为动态文本,并自动更新表格.根据我的经验,在表视图中,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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4260 次 |
| 最近记录: |