2017-02-12 7 views
0

Я использую UICollectionViewCell с кнопками внутри родительского UICollectionViewCell:Segue от кнопки с UICollectionViewCell внутри родительского UICollectionViewCell

protocol DayCellDelegate 
{ 
    func buttonTapped() 
} 

class SelectTimeViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate { 

    @IBOutlet weak var collectionViewSlider: UICollectionView!  

    override func viewDidLoad() { 
     super.viewDidLoad()    
     collectionViewSlider?.register(DayCollectionViewCell.self, forCellWithReuseIdentifier: "cell") 
     collectionViewSlider.dataSource = self 
     collectionViewSlider.delegate = self 
    } 

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 
     return 3 
    } 

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
     let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! DayCollectionViewCell 
     cell.dayTitle.text = String(indexPath.row) 
     return cell 
    } 
} 

class DayCollectionViewCell: UICollectionViewCell, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, DayCellDelegate { 

    func buttonTapped() { 
     print("button clicked") 
    } 

    override init(frame: CGRect) { 
     super.init(frame: frame) 
     setupDayTimeline(width: frame.width, height: frame.height) 
    } 

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

    func setupDayTimeline(width: CGFloat, height: CGFloat) { 

     let appsCollectionView: UICollectionView = { 
      let layout = UICollectionViewFlowLayout()    
      layout.itemSize = CGSize(width: 90, height: 45) 
      let collectionView = UICollectionView(frame: CGRect(x: 0, y: 30, width: width, height: height - 30), collectionViewLayout: layout)    
      return collectionView 
     }() 
     addSubview(appsCollectionView) 

     appsCollectionView.delegate = self 
     appsCollectionView.dataSource = self 

     appsCollectionView.register(UINib(nibName: "TimeCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "timecell") 
    } 

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 
     return 3 
    } 

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 

     let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "timecell", for: indexPath) as! TimeCollectionViewCell 
     cell.btnTime.addTarget(self, action: #selector(timeSelected), for: .touchUpInside) 
     }   
     return cell 
    } 

    func timeSelected(){ 
     //here I need perform segue for SelectTimeViewController 
    } 
} 

class TimeCollectionViewCell: UICollectionViewCell { 

    @IBOutlet weak var btnTime: UIButton!  
    var delegate : DayCellDelegate? 

    @IBAction func btnTimeClick(_ sender: Any) { 
     self.delegate?.buttonTapped() 
    } 

    override func awakeFromNib() { 
     super.awakeFromNib() 
    } 

Как я могу выполнить переход от DayCollectionViewCell? я не могу назвать self.performSegue (withIdentifier: «...», отправитель: информация) в timeSelected(), потому что UICollectionViewCell не содержит performSegue

ответ

1

Создать протокол для контроллера, который держит ваше представление коллекции, это протокол будет определять «сотовый делегат», а затем вы можете вызвать действия на контроллере, а именно:

protocol DayCellDelegate 
{ 
    func buttonTapped(...) 
} 

вы создаете свойство в DayCellCollectionViewCell или его родитель, вы можете назвать его делегируют

var delegate : DayCellDelegate? 

И п в методе cellForItem, когда вы можете ячейки, установить делегат к контроллеру и его реализации:

cell.delegate = self 

И, наконец, в действии крана вашей ячейки, звоните:

self.delegate?.buttonTapped(...) 

Надежда, что помогает, если вам нужно более конкретное руководство, дайте мне знать.

+0

Не забудьте сделать делегат переменной «слабый», чтобы избежать возможных циклов. Я считаю, что для этого протокол должен быть ограничен только классом –

+0

DayCollectionViewCell должен наследовать от DayCellDelegate и соответствовать протоколу, то есть иметь реализацию buttonTapped, а также – unkgd

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

  • Нет связанных вопросов^_^