2017-02-11 13 views
0

В моем swift приложении Я создал класс, который делегаты UICollectionViewController. Кроме того, у меня есть другой класс, ответственный за обработку «UICollectionReusableView».tapGestureRecognizer.location приносит nil в UICollectionView

Таким образом, в первом классе у меня есть метод:

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 тогда?

ответ

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) 

} 
+0

Благодаря @Pierce, он прекрасно работает – user3766930

+0

@ user3766930?! - Конечно, удачи! – Pierce

0

Попробуйте один

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

Handle жест

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; 
      } 
     } 
    } 
+0

спасибо, однако 'вар indelPath ...' линия по-прежнему бросает мне 'nil' здесь :( – user3766930

+0

вы получаете действие крана или расположение –