ios - tapGestureRecognizer.location 在 UICollectionView 中带来 nil

标签 ios swift swift3 uicollectionview uicollectionreusableview

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

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

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

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

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

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呢?

最佳答案

由于在按钮上设置了 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类的特殊属性,你可以将 View 转换成一个 >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)

}

关于ios - tapGestureRecognizer.location 在 UICollectionView 中带来 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42180495/

相关文章:

ios - iPhone X 的 KeyboardWillShowNotification 上的 Textview 移动速度高于预期

ios - iPhone 6 Plus 中的搜索图标变形 - 被压成蛋形

ios - 将按钮标签传递给另一个事件中的字符串

swift - 在与关闭时相同的 View Controller 中打开(快速)

ios - SKSpriteNode 从屏幕上消失后如何删除或销毁它

iphone - 点击状态栏时滚动到顶部

ios - 如何快速检查 UIImage 是否为空?

swift - 如何删除已经呈现的不需要的 View 而不是呈现需要的 View ?

Swift Mac Quick Look 显示图像

ios - 如何显示所有页面导航栏按钮