UIButton не работает в ячейке collectionView - PullRequest
0 голосов
/ 28 августа 2018

Я пытаюсь создать эту коллекцию ячеек вида с пейджинговым поведением. В каждой клетке; Я сделал анимацию флип карты. Но функция переворота не работает. Я знаю, что функция в порядке, потому что; перед тем, как создать эту модель UICollectionViewCell, я попробовал все в самом UICollectionView, и это сработало идеально. Но так как мне нужно поведение подкачки, мне нужно несколько страниц с просмотром карты внутри и в каждой ячейке, когда пользователь вкладывает карту, она должна перевернуться. Итак, после того как я перенес весь код из CollectionView в CollectionViewCell; вид карты перестал переворачиваться. Даже оператор print (...) не возвращается в Xcode. Так что, я думаю, Xcode не чувствует прикосновения пользователя Во всяком случае, я такой младший, поэтому буду признателен, если кто-то решит это. Вот код для моей коллекции ViewView:

import UIKit

class AK11ViewController: AltKategoriViewController, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource, UICollectionViewDelegate {

    var ak11cv: UICollectionView!
    private let ak11CellId = "ak11CellId"

    let image1Names = ["bear_first", "heart_second", "leaf_third"]

    override func viewDidLoad() {
        super.viewDidLoad()
        background()
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return image1Names.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = ak11cv.dequeueReusableCell(withReuseIdentifier: ak11CellId, for: indexPath) as! AK11PageCell
        //cell.translatesAutoresizingMaskIntoConstraints = false

        let image1Name = image1Names[indexPath.item]
        cell.cardView1.image = UIImage(named: image1Name)

        return cell
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: view.frame.width, height: view.frame.height)
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }

    private func background() {

        tabBarController?.tabBar.tintColor = UIColor.white
        tabBarController?.tabBar.isTranslucent = false

        navigationController?.navigationBar.prefersLargeTitles = false
        navigationController?.navigationBar.isTranslucent = true

        let ak11Layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        ak11Layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        ak11Layout.scrollDirection = .horizontal

        ak11cv = UICollectionView(frame: self.view.frame, collectionViewLayout: ak11Layout)
        ak11cv.dataSource = self
        ak11cv.delegate = self
        ak11cv.isPagingEnabled = true
        ak11cv.isUserInteractionEnabled = true
        ak11cv.backgroundColor = UIColor.brown

        ak11cv.register(AK11PageCell.self, forCellWithReuseIdentifier: ak11CellId)

        view.addSubview(ak11cv)

    }
}

А вот код для моей коллекции ViewCell:

import UIKit

class AK11PageCell: UICollectionViewCell {

    let mainCardView: UIView = {
        let mcv = UIView()
        mcv.translatesAutoresizingMaskIntoConstraints = false
        mcv.isUserInteractionEnabled = true
        return mcv
    }()

    let frontContainerView: UIView = {
        let fcv = UIView()
        fcv.translatesAutoresizingMaskIntoConstraints = false
        fcv.backgroundColor = .blue
        fcv.isUserInteractionEnabled = true
        return fcv
    }()

    let backContainerView: UIView = {
        let bcv = UIView()
        bcv.translatesAutoresizingMaskIntoConstraints = false
        bcv.backgroundColor = .purple
        bcv.isUserInteractionEnabled = true
        //bcv.isHidden = true
        return bcv
    }()

    let pageControlContainerView: UIView = {
        let pcv = UIView()
        pcv.translatesAutoresizingMaskIntoConstraints = false
        pcv.backgroundColor = .green
        pcv.isUserInteractionEnabled = false
        return pcv
    }()

    var cardView1: UIImageView = {
        let cv1 = UIImageView()
        cv1.translatesAutoresizingMaskIntoConstraints = false
        cv1.contentMode = .scaleAspectFit
        cv1.isUserInteractionEnabled = true
        cv1.image = UIImage(named: "bear_first")
        return cv1
    }()

    var cardView2: UIImageView = {
        let cv2 = UIImageView()
        cv2.translatesAutoresizingMaskIntoConstraints = false
        cv2.contentMode = .scaleAspectFit
        cv2.isUserInteractionEnabled = true
        cv2.image = UIImage(named: "heart_second")
        return cv2
    }()

    let flipToBack: UIButton = {
        let ftb = UIButton(type: .system)
        ftb.isUserInteractionEnabled = true
        ftb.translatesAutoresizingMaskIntoConstraints = false
        ftb.addTarget(self, action: #selector(flip), for: .touchUpInside)
        return ftb
    }()

    let flipToFront: UIButton = {
        let ftf = UIButton(type: .system)
        ftf.isUserInteractionEnabled = true
        ftf.translatesAutoresizingMaskIntoConstraints = false
        ftf.addTarget(self, action: #selector(flip), for: .touchUpInside)
        return ftf
    }()

    var flippedCard = false


    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = UIColor.cyan

        setupViews()

    }

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


    fileprivate func setupViews() {

        addSubview(mainCardView)
        mainCardView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: frame.width * 0.1).isActive = true
        mainCardView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: frame.width * -0.1).isActive = true
        mainCardView.topAnchor.constraint(equalTo: topAnchor, constant: frame.height * 0.05).isActive = true
        mainCardView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: frame.height * -0.25).isActive = true
        mainCardView.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
        mainCardView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true

        mainCardView.addSubview(frontContainerView)
        frontContainerView.leadingAnchor.constraint(equalTo: mainCardView.leadingAnchor).isActive = true
        frontContainerView.trailingAnchor.constraint(equalTo: mainCardView.trailingAnchor).isActive = true
        frontContainerView.topAnchor.constraint(equalTo: mainCardView.topAnchor).isActive = true
        frontContainerView.bottomAnchor.constraint(equalTo: mainCardView.bottomAnchor).isActive = true
        frontContainerView.centerXAnchor.constraint(equalTo: mainCardView.centerXAnchor).isActive = true
        frontContainerView.centerYAnchor.constraint(equalTo: mainCardView.centerYAnchor).isActive = true

        mainCardView.addSubview(backContainerView)
        backContainerView.leadingAnchor.constraint(equalTo: mainCardView.leadingAnchor).isActive = true
        backContainerView.trailingAnchor.constraint(equalTo: mainCardView.trailingAnchor).isActive = true
        backContainerView.topAnchor.constraint(equalTo: mainCardView.topAnchor).isActive = true
        backContainerView.bottomAnchor.constraint(equalTo: mainCardView.bottomAnchor).isActive = true
        backContainerView.centerXAnchor.constraint(equalTo: mainCardView.centerXAnchor).isActive = true
        backContainerView.centerYAnchor.constraint(equalTo: mainCardView.centerYAnchor).isActive = true

        frontContainerView.addSubview(cardView1)
        cardView1.centerXAnchor.constraint(equalTo: frontContainerView.centerXAnchor).isActive = true
        cardView1.centerYAnchor.constraint(equalTo: frontContainerView.centerYAnchor).isActive = true
        cardView1.leadingAnchor.constraint(equalTo: frontContainerView.leadingAnchor).isActive = true
        cardView1.trailingAnchor.constraint(equalTo: frontContainerView.trailingAnchor).isActive = true
        cardView1.topAnchor.constraint(equalTo: frontContainerView.topAnchor).isActive = true
        cardView1.bottomAnchor.constraint(equalTo: frontContainerView.bottomAnchor).isActive = true

        frontContainerView.addSubview(flipToBack)
        flipToBack.centerXAnchor.constraint(equalTo: frontContainerView.centerXAnchor).isActive = true
        flipToBack.centerYAnchor.constraint(equalTo: frontContainerView.centerYAnchor).isActive = true
        flipToBack.leadingAnchor.constraint(equalTo: frontContainerView.leadingAnchor).isActive = true
        flipToBack.trailingAnchor.constraint(equalTo: frontContainerView.trailingAnchor).isActive = true
        flipToBack.topAnchor.constraint(equalTo: frontContainerView.topAnchor).isActive = true
        flipToBack.bottomAnchor.constraint(equalTo: frontContainerView.bottomAnchor).isActive = true

        backContainerView.addSubview(cardView2)
        cardView2.centerXAnchor.constraint(equalTo: backContainerView.centerXAnchor).isActive = true
        cardView2.centerYAnchor.constraint(equalTo: backContainerView.centerYAnchor).isActive = true
        cardView2.leadingAnchor.constraint(equalTo: backContainerView.leadingAnchor).isActive = true
        cardView2.trailingAnchor.constraint(equalTo: backContainerView.trailingAnchor).isActive = true
        cardView2.topAnchor.constraint(equalTo: backContainerView.topAnchor).isActive = true
        cardView2.bottomAnchor.constraint(equalTo: backContainerView.bottomAnchor).isActive = true

        backContainerView.addSubview(flipToFront)
        flipToFront.centerXAnchor.constraint(equalTo: backContainerView.centerXAnchor).isActive = true
        flipToFront.centerYAnchor.constraint(equalTo: backContainerView.centerYAnchor).isActive = true
        flipToFront.leadingAnchor.constraint(equalTo: backContainerView.leadingAnchor).isActive = true
        flipToFront.trailingAnchor.constraint(equalTo: backContainerView.trailingAnchor).isActive = true
        flipToFront.topAnchor.constraint(equalTo: backContainerView.topAnchor).isActive = true
        flipToFront.bottomAnchor.constraint(equalTo: backContainerView.bottomAnchor).isActive = true

        addSubview(pageControlContainerView)
        pageControlContainerView.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
        pageControlContainerView.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
        pageControlContainerView.bottomAnchor.constraint(equalTo: mainCardView.bottomAnchor, constant: 20).isActive = true
        pageControlContainerView.heightAnchor.constraint(equalTo: heightAnchor, multiplier: 0.075).isActive = true

    }


    @objc func flip() {

        print("tabbed")
        flippedCard = !flippedCard

        let fromView = flippedCard ? backContainerView : frontContainerView
        let toView = flippedCard ? frontContainerView : backContainerView

        UIView.transition(from: fromView, to: toView, duration: 0.5, options: [.transitionFlipFromRight, .showHideTransitionViews])
    }

}

Пожалуйста, игнорируйте мою модель данных, потому что я еще не установил ее; Я просто хочу, чтобы мой mainCardView, который является суперпредставлением для frontCardView и backCardView, перевернулся. Но любые предложения для других вещей также приветствуются.

Спасибо!

1 Ответ

0 голосов
/ 28 августа 2018

Полагаю, для правильной регистрации действия кнопки / цели вам нужно объявить их ленивыми:

lazy var flipToBack: UIButton = {

lazy var flipToFront: UIButton = {

Это должно решить проблему с краном.

...