2016-11-05 2 views
0

У меня есть два класса:Segue из пользовательских программно Tableview внутри CollectionView

class FeedAndGroupsViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {} 

class eventsCustomCollectionCell: UICollectionViewCell, UITableViewDataSource, UITableViewDelegate {} 

... где класс CollectionView создает UITableView.

Я пытаюсь создать пользовательский segue при нажатии на tableViewCell. Я выполнил функцию tableView (didSelectRowAt) для tableView, которая отлично работает. Однако я не могу вызвать функцию выполнения из этой функции. Кто-нибудь знает, как это решить?

ответ

0

Это потому, что ваш класс eventsCustomCollectionCell является подклассом UICollectionViewCell, а не подклассом UIViewController.

func performSegue(withIdentifier identifier: String, sender: Any?) 

- метод, доступный в UIViewController. Таким образом, для решения вы можете создать протокол в eventsCustomCollectionCell, который может иметь метод

func cellClicked(cell: eventsCustomCollectionCell) 

и ваш FeedAndGroupsViewController может реализовать этот протокол и может вызывать performSegue.

Я написал скелетный код для вашего прецедента, вы можете обратиться к этому коду и начать работу.

class EventsCustomCollectionCell: UICollectionViewCell,UITableViewDelegate{ 
    weak var delegate : EventsCustomCollectionCellDelegate? 
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 
     delegate?.didClick(cell: self) 
    } 
} 

protocol EventsCustomCollectionCellDelegate : class{ 
    func didClick(cell:EventsCustomCollectionCell) 
} 

class FeedAndGroupsViewController: UIViewController,EventsCustomCollectionCellDelegate,UICollectionViewDataSource{ 
var collectionView : UICollectionView! 
var yourArrayForCollectionView = [String]() 

func didClick(cell:EventsCustomCollectionCell){ 
    if let index = collectionView.indexPath(for:cell){ 
     let object = yourArrayForCollectionView[index.row] 
     performSegue(withIdentifier: "Your segue identifier", sender: object) 
    } 
} 

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{ 
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Your cell reuse id", for: indexPath) as! EventsCustomCollectionCell 
    cell.delegate = self 
    return cell 
} 

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

Надеюсь, это поможет.

+0

Спасибо за вашу помощь! Я попробовал ваше решение, но, похоже, я не могу назвать делегата коллекцииViewCell в функции cellForItemAt. –

+0

Вы должны вызвать метод делегата в файле didSelectRowAt UITableViewDelegate в вашем UICollectionViewCell. Я обновил свой код. –

+0

Отлично! большое спасибо –

0

Это заставило меня немного крутить колеса. В моем случае у меня есть UITableViewCell с UICollectionView внутри него. В ячейке просмотра таблицы находится массив элементов. Я не смог получить доступ к этим элементам внутри ViewController для указанного индекса. Кроме того, не используя раскадровки, а не performSegue(withIdentifier: "Your segue identifier", sender: object) Я использовал self.navigationController?.pushViewController(detailVC, animated: true)

Вот что в итоге получилось для меня. Я должен был передать объект в функции протокола.

protocol NearbyTableViewCellDelegate : class{ 
    func didClick(cell: EatsItemNearbyTableCell, eat: Eats) 
} 


func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { 
     let eat = nearByEats[indexPath.row] 
     delegate?.didClick(cell: self, eat: eat) 
    } 

В ViewController:

extension EatsItemDetailVC: NearbyTableViewCellDelegate { 
    func didClick(cell: EatsItemNearbyTableCell, eat: Eats) { 
     let detailVC = EatsItemDetailVC() 
     detailVC.eat = eat 
     detailVC.currentLocation = currentLocation 
     self.navigationController?.pushViewController(detailVC, animated: true) 
    } 
} 
Смежные вопросы