2016-01-12 5 views
1

Так что это проект tvOS в Свифте. У меня есть пользовательский UICollectionViewCell с кнопкой в ​​качестве одного из своих подзонов. Я добавляю цель к кнопке, чтобы она могла интерпретировать клики. Вот упрощенная версия соответствующего кодаКак получить пресса UIButton для работы в UICollectionViewCell в Swift?

class CustomCell: UICollectionViewCell { 
    var button:UIButton! 

    override init(frame: CGRect) { 
     super.init(frame: frame) 

     button = UIButton(...) // Button is initialized with a frame 
     button.userInteractionEnabled = true 
     button.enabled = true 
     button.addTarget(self, action: "pressed:", forControlEvents: .PrimaryActionTriggered) 
     contentView.addSubview(button) 
    } 

    func pressed(sender: UIButton!) { 
     print("button pressed!") 
    } 
} 

По какой-то причине это никогда не распечатывает мое сообщение. Я пытался добавить «pressedEnded» к классу клеток, чтобы увидеть, если это доставалось и он вызывается

func pressesEnded(presses: Set<UIPress>, withEvent event: UIPressesEvent?) { 
     // If I put a breakpoint here it's reached 
} 

Любые предложения? Когда я запускаю его в симуляторе, кнопка может получить фокус, поэтому я не знаю, почему он не может получить никаких событий.

ответ

3

Итак, я выяснил, как это решить, хотя это обходное решение. В основном для UICollectionView мне нужно убедиться, что ячейка не может получить фокус.

Следующий У меня был didUpdateFocusInContext в CustomCell ранее. Это было то, что на самом деле оживляло кнопку, когда ячейка , но когда я проверил, кнопка никогда не фокусировалась. Я предполагаю, что это перехватывало это. Поэтому я удалил эту функцию из CustomCell, а вместо этого в нижней части моего файла я добавил эту функцию как расширение UIButton.

Это также могло быть сделано путем создания подкласса UIButton и использования этого вместо этого, но это был меньше кода (это, вероятно, идеальный способ). Таким образом, полный код выглядит следующим образом:

class MyCollection: UICollectionView, UICollectionViewDelegate { 
    // Need initializer functions as well as functions for creating CustomCell's. They're omitted because they're not relevant to the answer 

    func collectionView(collectionView: UICollectionView, canFocusItemAtIndexPath indexPath: NSIndexPath) -> Bool { 
     return false 
    } 
} 

class CustomCell: UICollectionViewCell { 
    var button:UIButton! 

    override init(frame: CGRect) { 
     super.init(frame: frame) 

     button = UIButton(...) // Button is initialized with a frame 
     button.userInteractionEnabled = true 
     button.enabled = true 
     button.addTarget(self, action: "pressed:", forControlEvents: .PrimaryActionTriggered) 
     self.addSubview(button) 
    } 

    func pressed(sender: UIButton!) { 
     print("button pressed!") 
    } 
} 

extension UIButton { 
    override public func didUpdateFocusInContext(context: UIFocusUpdateContext, withAnimationCoordinator coordinator: UIFocusAnimationCoordinator) { 
     super.didUpdateFocusInContext(context, withAnimationCoordinator: coordinator) 

     if self.superview is CustomCell { // This ensures that all UIButtons aren't affected 
      if context.nextFocusedView == self { 
       // Perform actions for when UIButton is focused 
      }else { 
       // Perform actions for when UIButton loses focus 
      } 
     } 
    } 
} 
-2

Над ответом является правильным, и если вы используете пользовательские UICollectionViewCell вы также можете сделать это в своем подклассе для специфических клеток:

override func canBecomeFocused() -> Bool { 
    return false 
} 
-2

Кажется UICollectionViewCell автоматически накладывается четким представлением, которое захватывает метчики.

Для нас только что вызвал bringSubview (toFront: checkButton). Теперь действие checkButton touchUpInside называется так, как должно.

import UIKit 

class SerieItemCollectionViewCell: UICollectionViewCell { 

    var checked : (()->())? 


    static let reuseIdentifier = "SerieItemCollectionViewCell" 

    @IBOutlet weak var checkButton: UIButton! 
    @IBOutlet var imageView: UIImageView! 

    override func layoutSubviews() { 
     super.layoutSubviews() 
     bringSubview(toFront: checkButton) 
    } 

    @IBAction func buttonClicked(_ sender: Any) { 
     checked?() 
     print("Hello") 
    } 
} 
-1

Взаимодействие Пользователь Enabled Флажок ключ!

Убедитесь, что установлен флажок Взаимодействие с пользователем для UICollectionViewCell. Затем действия кнопок будут работать, как ожидалось.

enter image description here

Смежные вопросы