在我的 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/