做過 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:];
,這時候跟 iOS14 之前是一緻的。cell - contentView - custom subviews
- 不添加任何控件,系統會自動建立出
- xib 建立
cell
- 由于在 xib 中,添加的控件全部是在
上的,是以跟 iOS14 是一緻的,視圖層級由下到上為contentView
cell - contentView - custom subviews
- 由于在 xib 中,添加的控件全部是在
繼續看
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
- 在 xib 中,不會顯示出
是以,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 ,運作可以清楚的看到不同情況下的效果,位址在這裡,需要的可以點選下載下傳。