モダンなCellの構成

Modern Cell Configuration

https://developer.apple.com/videos/play/wwdc2020/10027/

Session概要

UICollectoinView/TableView Cellの構成に関する新しい技術について
コンテンツを持つCellを簡単に作成し、共通のスタイルを適用するためのConfiguration typeについて学習します。
異なるstateによって、表現を変える方法や、
コードを簡略化し、バグを取り除き、パフォーマンスを向上させるパターンやベストプラクティスを学習します。

View Configuration

Content Configurationを使ったコンテンツの定義
var content = cell.defaultContentConfiguration()

content.image = UIImage(systemName: "star")
content.text = "Hello WWDC!"

cell.contentConfiguration = content
Configurationの生成はlightweightに出来るため、毎回Configurationを生成しstateを新しく出来る

Configuration State

Configuration StateではCellやReusableView(headerなど)のstateや自身が設定したcustom stateを一元管理出来、
個々のCellやReusableViewでStateを持つ
Custom Stateはkey value storeで管理

View Configuration State

  • Trait Collection
    • Highlighted
    • Selected
    • Disabled
    • Focused
  • Custom State

Cell Configuration State

Cell Configuration StateはView Configuration stateにプラスアルファで管理されているstateがある

Sample code

updateConfiguration methodでstateを受け取り、stateによってcontentの内容を変更する
override func updateConfiguration(using state: UICellConfigurationState) {
    var content = self.defaultContentConfiguration().updated(for: state)

    content.image = self.item.icon
    content.text = self.item.title

    if state.isHighlighted || state.isSelected {
        content.imageProperties.tintColor = .white
        content.textProperties.color = .white
    }

    self.contentConfiguration = content
}
contentConfiguration にcontentをsetすることにより、毎回新しいstateに反映させている

Background and Content Configurations

UICollectionViewCell, UITableViewCellともにDefaultではbackground configrautionが自動的に設定される

Background Configuration

  • 背景色
  • 視覚効果
  • ストローク
  • Inset, corner radius(角丸)
  • カスタムView

List Content Configuration

  • Image
  • Text
  • セカンダリーText
  • レイアウト、振る舞い
text sizeが変わっても自動的にself sizingを行う



List Cell内でImageとTextを表示した際に、ImageとTextの間を均等に設定しているために、ImageのwidthによってTextの開始位置がズレることがある



このような問題をreserved layout sizeを設定することで簡単に解決できる。
赤の点線がreserved layout sizeでこの位置から均等にTextとのpaddingを設定するように実装出来る。
reserved layout sizeは実際の画像サイズの影響は受けず、画像サイズがreserved layout sizeよりも大きい場合は、領域外にはみ出すことが許可される。



List Content Viewの作り方
var content = UIListContentConfiguration.cell()

// Set up the content configuration as desired...

let contentView = UIListContentView(configuration: content)
最新情報をチェックしよう!