YeahGarage
@YeahGarage
Developer

Как реализовать Выбор ячейки в UICollectionView didSelectItemAt?

Приветствую
Первый раз работаю с UICollectionView и делаю программно, не могу добиться срабатывания метода func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
Буду очень признателен за Ваши советы

Код следующий
class UserViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {

let collectionView: UICollectionView = {
    let layout = UICollectionViewFlowLayout()
    layout.minimumLineSpacing = 16
    layout.scrollDirection = .vertical
    let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
    cv.backgroundColor = .clear
    return cv
}()

let layout = UICollectionViewFlowLayout()

override func viewDidLoad() {
    super.viewDidLoad()
    setupViews()
}

 func setupViews() {
    collectionView.register(videoCell.self, forCellWithReuseIdentifier: imagesCellId)
    collectionView.register(previewCell.self, forCellWithReuseIdentifier: albumCellId)
    collectionView.delegate = self
    collectionView.dataSource = self
    collectionView.allowsSelection = true
    collectionView.isUserInteractionEnabled = true
    view.addSubview(collectionView)
    collectionView.translatesAutoresizingMaskIntoConstraints = false
    collectionView.topAnchor.constraint(equalTo: view.topAnchor, constant: 20).isActive = true
    collectionView.bottomAnchor.constraint(equalTo:  view.bottomAnchor, constant: 5).isActive = true
    collectionView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 0).isActive = true
    collectionView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 0).isActive = true
}


func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if indexPath.section == 1 {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: albumCellId, for: indexPath) as! previewCell
return cell
}
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: imagesCellId, for: indexPath) as! videoCell
return cell
}
}


func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
self.collectionView.selectItem(at: IndexPath(item: 0, section: 0), animated: true, scrollPosition: .left)
self.collectionView(self.collectionView, didSelectItemAt: IndexPath(item: 0, section: 0))
}



////////////////////////////////////////////////
////////////////////////////////////////////////




class videoCell: UICollectionViewCell, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource, AVPlayerViewControllerDelegate, UIGestureRecognizerDelegate {

let collectionView: UICollectionView = {
    let layout = UICollectionViewFlowLayout()
    layout.minimumLineSpacing = 30
    layout.scrollDirection = .horizontal
    let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
    cv.backgroundColor = UIColor.clear
    //cv.allowsSelection = true
    return cv
}()

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

func setup() {
    addSubview(collectionView)
    collectionView.translatesAutoresizingMaskIntoConstraints = false
    collectionView.topAnchor.constraint(equalTo: self.topAnchor, constant: 15).isActive = true
    collectionView.bottomAnchor.constraint(equalTo:  self.bottomAnchor, constant: 15).isActive = true
    collectionView.rightAnchor.constraint(equalTo: self.rightAnchor, constant: 5).isActive = true
    collectionView.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 5).isActive = true
    collectionView.delegate = self
    collectionView.dataSource = self
    collectionView.allowsSelection = true
    collectionView.isUserInteractionEnabled = true
    collectionView.register(InsideVideoCell.self, forCellWithReuseIdentifier: videCellId)
    tap.delegate = self
    tap.cancelsTouchesInView = false
    tap.isEnabled = true
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: videCellId, for: indexPath) as! InsideVideoCell
return cell
}

required init?(coder aDecoder: NSCoder) {
    fatalError("Error VideoCell")
}


 private class InsideVideoCell: UICollectionViewCell {
public var videoPlayerController = AVPlayerViewController()
.....
}
  • Вопрос задан
  • 1194 просмотра
Решения вопроса 1
Из того кода, что написан, максимально приближенный рабочий вариант будет выглядеть следующим образом. Чтобы хорошо разобраться в теме рекомендую посмотреть этот курс по Collection View.
import UIKit
import AVKit

class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
    
    let imagesCellId = "ImageCellId"
    let albumCellId = "AlbumCellId"
    
    let collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 16
        layout.scrollDirection = .vertical
        layout.itemSize = CGSize(width: 50, height: 50)
        
        let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
        cv.backgroundColor = .clear
        
        return cv
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupViews()
    }
    
    func setupViews() {
        collectionView.register(VideoCell.self, forCellWithReuseIdentifier: imagesCellId)
        collectionView.register(PreviewCell.self, forCellWithReuseIdentifier: albumCellId)
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.allowsSelection = true
        collectionView.isUserInteractionEnabled = true
        
        view.addSubview(collectionView)
        
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        collectionView.topAnchor.constraint(equalTo: view.topAnchor, constant: 20).isActive = true
        collectionView.bottomAnchor.constraint(equalTo:  view.bottomAnchor, constant: 5).isActive = true
        collectionView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 0).isActive = true
        collectionView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 0).isActive = true
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if indexPath.section == 1 {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: albumCellId, for: indexPath) as! PreviewCell
            cell.backgroundColor = UIColor.red
            return cell
        }
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: imagesCellId, for: indexPath) as! VideoCell
        
        cell.backgroundColor = UIColor.green
        return cell
    }
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 2
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        // Вот тут совсем не понятно, что хотел сказать автор
        
//        collectionView.selectItem(at: IndexPath(item: 0, section: 0), animated: true, scrollPosition: .left)
//        collectionView(collectionView, didSelectItemAt: IndexPath(item: 0, section: 0))
        
        print("Выбрана ячейка: (\(indexPath.section), \(indexPath.item))")
    }
    
}

class VideoCell: UICollectionViewCell, AVPlayerViewControllerDelegate {
    var videoPlayerController = AVPlayerViewController()
}
class PreviewCell: UICollectionViewCell {

}
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы