tapGestureRecognizer.location 在 UICollectionView 中引入 nil

tapGestureRecognizer.location brings nil in UICollectionView

在我的 swift 应用程序中,我创建了 class 委托 UICollectionViewController。此外,我还有其他 class 负责处理“UICollectionReusableView”。

所以在第一个class我有一个方法:

override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {

    let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "Header", for: indexPath) as! UserProfileHeaderCollectionReusableView

多亏了这个 - 在这个方法中 - 我可以访问存储在 header 视图中的所有按钮和标签,例如:

headerView.followButton.isHidden = false

headerView.followButton.addGestureRecognizer(
           UITapGestureRecognizer(target: self, action: #selector(followThisUser)))

稍后,我有一个方法followThisUser:

@objc private func followThisUser(tapGestureRecognizer: UITapGestureRecognizer) {

    if (!doIFollow) {

        followUser(userId)
    } else {
        unfollowUser(userId)
    }
}

并根据标志 doIFollow 我正在执行特定方法。

我想在用户按下按钮时给予反馈,并在按下按钮后立即更改颜色。我试图通过添加访问此按钮:

    let tapLocation = tapGestureRecognizer.location(in: self.userProfileCollectionView)

    let indexPath : NSIndexPath = self.userProfileCollectionView.indexPathForItem(at: tapLocation)! as NSIndexPath

followThisUser 方法,但它抛出错误:

fatal error: unexpectedly found nil while unwrapping an Optional value

那我怎样才能访问 followButton

试试这个

var tapGesture : UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "processTapGesture:")
        tapGesture.numberOfTapsRequired = 1
        collectionView.addGestureRecognizer(tapGesture)

手柄手势

func processTapGesture (sender: UITapGestureRecognizer)
    {
        if sender.state == UIGestureRecognizerState.Ended
        {
            var point:CGPoint = sender.locationInView(collectionView)
            var indelPath:NSIndexPath =collectionView.indexPathForItemAtPoint(point)
            if indexPath
            {
                print("image taped")
            }
            else
            {
               //Do Some Other Stuff Here That Isnt Related;
            }
        }
    }

由于在按钮上设置了 UITapGestureRecognizer,您可以做的是从处理程序方法中的手势识别器获取原始 UIView。像这样将按钮背景颜色变为橙色:

@objc private func buttonTap(tapGestureRecognizer: UITapGestureRecognizer) {

    // Get the view that the gesture is attached to
    let button = tapGestureRecognizer.view

    // Change the view's background color
    button?.backgroundColor = UIColor.orange

}

现在,如果您的原始按钮是 UIButton,并且您需要使用 UIButton class 的一些特殊属性,您可以将视图转换为 UIButton

@objc private func buttonTap(tapGestureRecognizer: UITapGestureRecognizer) {

    // Get the view that the gesture is attached to
    let button = tapGestureRecognizer.view as! UIButton

    // Change the UIButton's title label text color
    button.setTitleColor(UIColor.orange, for: .normal)

}