uitapgesture реагирует только после 3 нажатий - PullRequest
0 голосов
/ 18 декабря 2018
  1. У меня есть MasterController: UIViewController
  2. Внутри есть UIView (mainViewContainer) -> self.frame
  3. mainViewContainer содержит MainViewController: UIViewController
  4. MainViewController имеетmainCollectionView: UICollectionView .horizontally с 3 ячейками
  5. ячейки mainCollectionView содержат UITableView внутри *

Я добавил UITapGestureRecognizer в представление MasterController для выполнения действия в UITableView.

Он отлично работает в первом CollectionViewCell, но когда я прокручиваю до следующей ячейки, жест касания реагирует только после 3 нажатий, но я хочу, чтобы он реагировал на первое касание, как и в первой ячейке.

Примечание: после 3-х нажатий он начинает нормально работать на одиночных нажатиях.это происходит только тогда, когда приложение инициализируется после сборки.

Это в моем tableViewCell:

class CustomTableViewCell: UITableViewCell {

  let customView: UIView = {
     let view = UIView()
     view.backgroundColor = .white
     view.translatesAutoresizingMaskIntoConstraints = false
     return view
  }()

  let moreButton: UIButton = {
        let button = UIButton(type: .system)
        button.setImage(#imageLiteral(resourceName: "moreButton").withRenderingMode(.alwaysOriginal), for: .normal)
        button.contentMode = .scaleAspectFit
        button.translatesAutoresizingMaskIntoConstraints = false
        return button
    }()

  lazy var tapGesture: UITapGestureRecognizer = {
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTapGesture(_:)))
        tapGesture.cancelsTouchesInView = false
        return tapGesture
    }()

  var master = UIApplication.shared.keyWindow?.rootViewController as? MasterViewController

  var isCustomViewOpen = false

  override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        setupCustomView()
        setupMoreButton()

        master?.view.addGestureRecognizer(tapGesture)
  }

  func setupCustomView() {
        customView.layer.cornerRadius = 7
        addSubview(customView)
        NSLayoutConstraint.activate([
            customView.topAnchor.constraint(equalTo: topAnchor, constant: 10),
            customView.leftAnchor.constraint(equalTo: leftAnchor, constant: 10),
            customView.rightAnchor.constraint(equalTo: rightAnchor, constant: -10),
            customView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -10),
            ])
    }

    func setupMoreButton() {
        customView.addSubview(moreButton)
        moreButton.addTarget(self, action: #selector(handleMoreButton(_:)), for: .touchDown)
        NSLayoutConstraint.activate([
            moreButton.heightAnchor.constraint(equalToConstant: 15),
            moreButton.widthAnchor.constraint(equalToConstant: 20),
            moreButton.centerYAnchor.constraint(equalTo: customView.centerYAnchor),
            moreButton.trailingAnchor.constraint(equalTo: customView.trailingAnchor, constant: -20)
            ])
    }

    @objc func handleMoreButton(_ sender: UIButton) {
        isCustomViewOpen ? slideCustomViewRight() : slideCustomViewLeft()
    }

    func performAnimations(transform: CGAffineTransform) {
        UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: {
            self.customView.transform = transform
        })
    }

    func slideCustomViewLeft() {
        isCustomViewOpen = true
        performAnimations(transform: CGAffineTransform(translationX: -self.frame.width/3.2, y: 0))
        tapGesture.isEnabled = true
    }

    func slideCustomViewRight() {
        isCustomViewOpen = false
        performAnimations(transform: .identity)
        tapGesture.isEnabled = false
    }

    @objc func handleTapGesture(_ sender: UITapGestureRecognizer) {
        slideCustomViewRight()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }


}

1 Ответ

0 голосов
/ 18 декабря 2018

Я пытался shouldRecognizeSimultaneouslyWith otherGestureRecognizer: раньше, но я думаю, что где-то делал что-то не так.

благодаря @Scriptable в комментариях я попробовал еще раз и теперь работает.Мы должны всегда возвращаться и пытаться снова, если ничего не работает.

решается следующим образом:

сначала добавлена ​​функция делегата в MasterViewController ->

extension MasterViewController: UIGestureRecognizerDelegate {

    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        return true
    }
}

А затем добавлен делегатнажать жест ->

var master = UIApplication.shared.keyWindow?.rootViewController as? MasterViewController

tapGesture.delegate = master
...