UICollectionView IOS中标头的操作

时间:2014-07-22 09:47:01

标签: ios objective-c uicollectionview

我的代码中的集合中有不同数量的标头,当我单击标题时,每个标头都有不同的操作。如果我选择一个单元格,则调用- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath方法。那么,当选择任何补充视图时,是否有任何委托方法?

2 个答案:

答案 0 :(得分:6)

@Geet是Swift 5的答案。使用委派只有9个简单步骤

// 1. create a protocol outside of your headerView class
protocol YourHeaderViewDelegate: class {

    // 2. create a function that will do something when the header is tapped
    func doSomething()
}

class YourHeaderView: UICollectionReusableView {

    // 3. inside the headerView set a property named delegate of type YourHeaderViewDelegate? and make sure it's optional
    weak var delegate: YourHeaderViewDelegate?

    override init(frame: CGRect) {
        super.init(frame: frame)

        // 4. add a tapGesture to your headerView
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(headerViewTapped))
        addGestureRecognizer(tapGesture)
    }

    // 5. inside the selector method for the tapGestureRecognizer call the property and then call the doSomething method
    @objc func headerViewTapped() {

        delegate?.doSomething()
    }
}

// 6. make sure the class with the headerView's collectionView conforms to YourHeaderViewDelegate
class ClassWithCollectionView: YourHeaderViewDelegate {

    // 7. inside the class with your collectionView when you create the headerView make to set the delegate as self
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "headerViewId", for: indexPath) as! YourHeaderView

        // 8. *** set this to self ***
        headerView.delegate = self

        return headerView
    }

    // 9. since your class conforms to the YourHeaderViewDelegate method when you tap the headerView this function will get called
    func doSomething() {

        print("hello!")
    }
}

答案 1 :(得分:2)

尝试在您的视图中添加访客,例如

UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]
                               initWithTarget:self
                               action:@selector(handleTapGuesture)];

[headerView addGestureRecognizer:tap];

将此代码放在setUp HeaderView

的位置

然后实现 - (void)handleTapGuesture;执行行动的方法