![](/img/trans.png)
[英]How can I have multiple Collection Views in one View Controller?
[英]How to have a view controller with two collection views, but only one has header/footer views?
我的視圖 controller 中有兩個集合視圖,它們被設置為兩者的委托和數據源。 其中一個集合視圖有一個注冊的補充視圖作為它的 header,它在我添加第二個集合視圖之前將其出列並正確顯示。 現在使用第二個集合視圖, viewForSupplementaryElementOfKind
會導致錯誤,因為第二個集合視圖沒有任何注冊的標頭。 如何確保僅在第一個集合視圖上調用 function?
為 UICollectionView 創建一個簡單而簡短的自定義子類,如下所示:
class CustomCollectionView : UICollectionView {
let showFooter : Bool
let showHeader : Bool
init(showHeader:Bool,showFooter:Bool) {
self.showFooter = showFooter
self.showHeader = showHeader
//Create a custom UICollectionViewLayout and frame according to your requirement here (You can send parent ViewControllers frame as a param in the init above too)
super.init(frame: CGRect.zero, collectionViewLayout: UICollectionViewLayout.init())
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
現在只需使用 showHeader 和/或 showFooter 將第一個 CollectionView 初始化為 true 和其他相應的。您現在需要在請求補充視圖的委托回調中執行以下操作:
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
guard let collectionView = collectionView as? CustomCollectionView else {
return UICollectionReusableView.init(frame: .zero)
}
switch kind {
case UICollectionView.elementKindSectionFooter:
if collectionView.showFooter {
//Dequeue a footer and return
}
case UICollectionView.elementKindSectionHeader:
if collectionView.showHeader {
//Dequeue a header and return
}
default:
return UICollectionReusableView.init(frame: .zero)
}
return UICollectionReusableView.init(frame: .zero)
}
各種數據源和委托方法的第一個參數是集合視圖。
我不建議像其他海報建議的那樣使用視圖標簽。 這種方法很脆弱。
相反,讓您的視圖 controller 保留指向每個的指針,然后讓方法檢查正在調用哪個:
@IBOulet collectionView1: UICollectionView!
@IBOulet collectionView2: UICollectionView!
然后在您的 viewForSupplementaryElementOfKind 方法中:
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
switch collectionView {
case collectionView1:
//code to return a view for collection view 1
case collectionView2:
//code to return a view for collection view 2
default:
//Can't happen, but keep the compiler happy:
return UIView(frame: CGRect.zeroRect)
}
}
或者,設置單獨的對象作為每個集合視圖的數據源。 讓您的視圖 controller 創建數據源並將它們連接到其 viewDidLoad 方法中。
如果一個集合視圖具有 header 而另一個沒有,則需要為每個集合視圖單獨配置布局對象。 (您需要有類似上面的代碼,為您的所有集合視圖方法分別處理兩個集合視圖。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.