天天看點

iOS14 UITableViewCell & UICollectionViewCell 中還是乖乖使用 contentView 吧

做過 iOS 開發的,一般都使用過

UITableView

UICollectionView

,也就會用到

UITableViewCell

UIColletionViewCell

,在 iOS14 之前,使用

UITableViewCell

或者

UICollectionViewCell

添加控件的時候,不管使用

[self addSubview:];

還是使用

[self.contentView addSubview:];

,最後的視圖層級都是一樣的。但是在 iOS14 上,視圖層級發生了一些變化。而這個變化,會影響到

cell

上面子控件的點選。

在 iOS14 之前,不管是

UITableViewCell

還是

UICollectionViewCell

,不管使用

self

還是

self.contentView

亦或是 xib 添加控件,最後的視圖層級由下到上都是

cell - contentView - custom subviews

,其中

custom subviews

代表自己添加的控件。

在 iOS14 上,

UITableViewCell

UICollectionViewCell

的視圖層級已經不一樣了。

先看下

UITableViewCell

  • 代碼建立

    cell

    • 不添加任何控件,系統會自動建立出

      contentView

      ,視圖層級由下到上為

      cell - contentView

    • 如果使用

      [self addSubview:];

      添加控件,視圖層級由下到上會變成

      cell - custom subviews - contentView

      ,這時候添加的控件在

      contentView

      下面,如果子控件有點選事件,會被

      contentView

      阻斷掉
    • 如果使用

      [self.contentView addSubview:];

      添加控件,視訊層級由下到上會變成

      cell - contentView - custom subviews

      ,這時候跟 iOS14 之前是一緻的。
  • xib 建立

    cell

    • 由于在 xib 中,添加的控件全部是在

      contentView

      上的,是以跟 iOS14 是一緻的,視圖層級由下到上為

      cell - contentView - custom subviews

繼續看

UICollectionViewCell

  • 代碼建立

    cell

    • 不添加任何控件,系統不會自動建立

      contentView

      ,此時隻有

      cell

      ;
    • 如果使用

      [self addSubview:];

      添加控件,視圖層級由下到上會變成

      cell - custom subviews

    • 如果使用

      [self.contentView addSubview:];

      添加控件,視圖層級由下到上會變成

      cell - contentView - custom subviews

  • xib 建立

    cell

    • 在 xib 中,不會顯示出

      contentView

      ,直覺上看到的就是控件直接加到了

      cell

      上,但是運作之後,系統還是自動建立出

      contentView

      ,視圖層級由下到上是

      Cell - contentView - added subviews

是以,iOS14 上面,

UITableViewCell

UICollectionViewCell

偷偷的變化了。如果之前有使用

[self addSubview:];

這個方法直接添加視圖,可能就會發現界面看起來沒有任何問題,但是

UITableViewCell

裡面的點選事件單單在 iOS14 上無效了。那解決方案就是使用

[self.contentView addSubview:];

替代

[self addSubview:];

其實,通過上面不同情況的對比,可以發現不同層級确實不會影響顯示效果,而是會影響

cell

子控件的點選效果,而且僅僅是

UITableViewCell

才會出現這種問題。不過随着系統的繼續疊代,

UICollectionViewCell

會不會發生變化就不一定了。

而且,使用 xib 建立

cell

的話,表現跟 iOS14 之前是一緻的,并且使用

[self.contentView addSubview:];

也是一緻的。

還有,系統規範也已經說明了:

// UITableViewCell
// Custom subviews should be added to the content view.
@property (nonatomic, readonly, strong) UIView *contentView;

// UICollectionViewCell
@property (nonatomic, readonly) UIView *contentView; // add custom subviews to the cell's contentView
           

是以,我們不管是為了解決目前遇到的問題,還是為了防止以後再次出現這種問題,都應該使用

[self.contentView addSubview:];

添加控件。

我自己做了個 demo ,運作可以清楚的看到不同情況下的效果,位址在這裡,需要的可以點選下載下傳。

繼續閱讀