在我的swift
应用中,我创建了代表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
并且由于这个 - 在这种方法中 - 我可以访问存储在标题视图中的所有按钮和标签,例如:
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
呢?
答案 0 :(得分:1)
您可以执行的操作,因为您在按钮上设置了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
类的某些特殊属性,则可以将视图转换为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)
}
答案 1 :(得分:0)
试试这个
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;
}
}
}