テーブルビューに入る前に、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、テーブルビューはを観察します。テキストのサイズ変更が表示されるかどうかは、ダイナミックタイプがセルのラベルに使用されているかどうかの積です。あなたは以下のようなダイナミックテキストを、使用する場合は、(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