【发布时间】:2020-01-02 08:30:14
【问题描述】:
视图:页眉视图
class HeaderCell: UICollectionViewCell {
//MARK: - Properties
....
lazy var clearButton: UIButton = {
let bt = UIButton(type: .custom)
bt.backgroundColor = .clear
bt.addTarget(self, action: #selector(handleClearButton(button:)), for: .touchUpInside)
return bt
}()
weak var delegate: HeaderCellDelegate?
//MARK: - Init
required init?(coder aDecoder: NSCoder) {
return nil
}
override init(frame: CGRect) {
super.init(frame: frame)
configureCell()
addViews()
setConstraints()
}
....
//MARK: - Handlers
@objc func handleClearButton(button: UIButton) {
delegate?.expandSelectedHeader(self)
}
协议:HeaderCellDelegate
protocol HeaderCellDelegate: class {
func expandSelectedHeader(_ header: UICollectionViewCell)
}
控制器:SomeController
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
switch kind {
case UICollectionView.elementKindSectionHeader:
let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: reuseIdentifierForHeader, for: indexPath) as! HeaderCell
header.toMenuControllerDelegate = self
return header
case UICollectionView.elementKindSectionFooter:
let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: reuseIdentifierForFooter, for: indexPath) as! MenuFooterCell
return footer
default:
return UICollectionReusableView()
}
}
extension SomeController:HeaderCellDelegate {
func expandSelectedHeader(_ header: UICollectionViewCell) {
let indexPath = collectionView.indexPath(for: header)
print(indexPath)
}
}
我正在尝试在 headerView 中使用 clearButton,当点击按钮时,它会将自身(UIcollectionViewCell)发送到控制器。因此,一旦控制器接收到有关单元格的信息,我就可以使用collectionView.indexPath(for cell:UICollectionViewCell) 来获取点击按钮的标题的 indexPath。但是使用上面的代码,我只能得到nil 和print(indexPath)。
我该如何解决这个问题??? 我提前感谢您的帮助。
【问题讨论】:
标签: ios swift uicollectionview