Swift Добавление различных действий к ячейкам в UICollectionView - PullRequest
2 голосов
/ 12 июля 2020

Я не знаю, с чего начать, у меня есть UICollectionView с несколькими ячейками, заполненными UIImage. Я хочу, чтобы каждая ячейка / UIImage выполняла другое действие на касании пальца. Может ли кто-нибудь указать мне в правильном направлении? Думаю, мне нужно что-то сделать с let cell = countryCollectionView.dequeueReusableCell?

import UIKit

class ViewController: UIViewController, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {

    @IBOutlet weak var soundsCollectionView: UICollectionView!
    
    lazy var cv: UICollectionView = {
    let layout = UICollectionViewFlowLayout()
    layout.scrollDirection = .vertical
        
    var cc = UICollectionView(frame: .zero, collectionViewLayout: layout)
    cc.translatesAutoresizingMaskIntoConstraints = false
    cc.register(CustomCell.self, forCellWithReuseIdentifier: "CustomCell")
    cc.delegate = self
    cc.dataSource = self
    cc.backgroundColor = .white
    return cc
    }()
    
        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view.
            
            view.addSubview(cv)
            cv.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
            cv.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
            cv.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
            cv.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
            
        }
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 10
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CustomCell", for: indexPath) as! CustomCell
        cell.tag = indexPath.row
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: view.frame.width, height: 100)
    }
    
}

class CustomCell: UICollectionViewCell {
    
    lazy var centerImageView: UIImageView = {
        var img = UIImageView()
        img.translatesAutoresizingMaskIntoConstraints = false
        img.image = UIImage(named: "1")
        img.clipsToBounds = true
        img.isUserInteractionEnabled = true
        
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handler(_:)))
        tapGesture.numberOfTapsRequired = 1
        
        img.addGestureRecognizer(tapGesture)
        
        return img
    }()
    
    @objc private func handler(_ sender: UITapGestureRecognizer) {
        print("tapped tag > ", self.tag)
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        addSubview(centerImageView)
        centerImageView.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
        centerImageView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
        centerImageView.heightAnchor.constraint(equalToConstant: 80).isActive = true
        centerImageView.widthAnchor.constraint(equalToConstant: 80).isActive = true
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

Ответы [ 2 ]

1 голос
/ 12 июля 2020

Я редактирую как новый программный пример решения вашей проблемы.

class ViewController: UIViewController, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {
    
    lazy var cv: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .vertical
        
        var cc = UICollectionView(frame: .zero, collectionViewLayout: layout)
        cc.translatesAutoresizingMaskIntoConstraints = false
        cc.register(CustomCell.self, forCellWithReuseIdentifier: "CustomCell")
        cc.delegate = self
        cc.dataSource = self
        cc.backgroundColor = .white
        return cc
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.addSubview(cv)
        cv.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
        cv.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
        cv.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
        cv.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
    }
    
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 10
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CustomCell", for: indexPath) as! CustomCell
        cell.tag = indexPath.row
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: view.frame.width, height: 100)
    }
    
    
}


class CustomCell: UICollectionViewCell {
    
    lazy var centerImageView: UIImageView = {
        var img = UIImageView()
        img.translatesAutoresizingMaskIntoConstraints = false
        img.image = UIImage(named: "1")
        img.clipsToBounds = true
        img.isUserInteractionEnabled = true
        
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handler(_:)))
        tapGesture.numberOfTapsRequired = 1
        
        img.addGestureRecognizer(tapGesture)
        
        return img
    }()
    
    @objc private func handler(_ sender: UITapGestureRecognizer) {
        print("tapped tag > ", self.tag)
    }
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        
        
        addSubview(centerImageView)
        centerImageView.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
        centerImageView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
        centerImageView.heightAnchor.constraint(equalToConstant: 80).isActive = true
        centerImageView.widthAnchor.constraint(equalToConstant: 80).isActive = true
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
0 голосов
/ 15 июля 2020

В этом случае я бы не использовал кнопки на ваших ячейках. Вместо этого вы должны подключиться к методу делегата didSelectItemAt и просто добавить необходимую информацию в модель данных:

struct Country {
    let imageName: String
    let sound: Sound // You didn't specify what type the sound1 object is but you get the gist
}

Итак, массив стран теперь будет содержать эту новую структуру, а не только необработанные строки :

let countries = [
    Country("country1", sound1),
    Country("country2", sound2),
    ...
]

Затем вы можете получить именно тот звук, который хотите воспроизвести, из indexPath, переданного в didSelectItemAt:

let sound = self.countries[indexPath.row].sound
sound.play()

Вам также нужно будет настроить, как вы устанавливаете изображение ячейки в cellForItemAt:

let imageName = self.countries[indexPath.row].imageName
cell.countryImageView.image = UIImage(named: imageName)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...