【发布时间】:2017-05-24 09:28:45
【问题描述】:
几个小时以来我一直试图解决这个问题,但没有找到合适的解决方案。我想在标题中有一个带有分段控件的自定义 UICollectionView。更改分段控制索引应该以不同方式呈现单元格。到目前为止,我可以在我的 collectionView 的标题中显示分段控件,但是在我的 UserSearchHeader 中更改 collectionView 的内容不起作用。
我创建了一个名为 UserSearchController 的自定义 UICollectionView,它是 UICollectionView 的子类,符合 UICollectionViewDelegateFlowLayout 协议。
class UserSearchController: UICollectionViewController,
UICollectionViewDelegateFlowLayout, UISearchBarDelegate { ....
我的自定义 collectionView UserSearchController 有一个自定义标题 (UserSearchHeader) 和自定义单元格 (UserSearchCell)。
collectionView?.register(UserSearchCell.self, forCellWithReuseIdentifier: cellId)
collectionView?.register(UserSearchHeader.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "headerId")
UserSearchHeader 包含分段控件。
class UserSearchHeader: UICollectionViewCell {
var segmentedControl: UISegmentedControl = {
let sc = UISegmentedControl(items: ["Username", "Hashtag"])
sc.translatesAutoresizingMaskIntoConstraints = false
sc.tintColor = UIColor.black
sc.selectedSegmentIndex = 0 // automatically highlight
// sc.addTarget(self, action: #selector(segmentedChange), for: .valueChanged)
return sc
}() .....
如果 segmentedIndex 为 0,我想用 UserSearchCell 类渲染单元格,如果 segmentedIndex 为 1,我想用不同的 cellClass 渲染它(单击分段控件)。如何使用这些不同的类实现这种行为。我应该在 UserSearchController 内部的方法中使用 cellForItem 来检查分段控件的状态。但是,当在 UserSearchHeader 类中定义分段控件时,我该怎么做。
override func collectionView(_ collectionView:
UICollectionView, cellForItemAt indexPath: IndexPath) ->
UICollect. ionViewCell { if segmentedControl.segmentedIndex = 0 ....}
【问题讨论】:
-
是的,您可以轻松地执行此操作,更改选定索引后,您需要重新加载集合视图,并在索引路径的 cellforrow 中检查选定索引是否为零返回单元格1,如果选定索引为 1,则返回单元格2
-
我试过了,但这不起作用,因为segmentedControl是在UserSearchHeader中定义的。内容没有变化,因为分段控件的targetAction没有执行
-
OK 然后制定协议,一旦选择的索引更改就会通知您,并且还会传递您选择的索引。
-
谢谢,但我不知道该怎么做,你能根据我的课程给我一个简短的例子吗?它会对我有很大帮助。
-
好的,请给我发送代码,如果可以的话,我会这样做
标签: ios swift uicollectionview uicontrol