как получить строку табличного представления и pu sh для viewController из collectionView, который находится внутри tableViewCell при нажатии кнопки внутри ячейки collectionView - PullRequest
0 голосов
/ 16 января 2020

Моя иерархия такая, как эта ячейка, я установил так:

protocol CustomCollectionCellDelegate:class {
func collectionView(collectioncell:AccountTypeCollectionViewCell?, didTappedInTableview TableCell:AccountTypeTableViewCell, collectionRow: Int)
func OpenNows(wasPressedOnCell cell: AccountTypeCollectionViewCell?)}

class AccountTypeTableViewCell: UITableViewCell, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
    weak var cellDelegate:CustomCollectionCellDelegate?
    weak var myParent:AccountTypeViewController?
    @IBOutlet weak var collectionAccountTypeView: UIView!
    @IBOutlet weak var lblAccountTypeTitle: UILabel!
    @IBOutlet weak var collectionView: UICollectionView!
    let cellReuseId = "CollectionViewCell"
    class var customCell : AccountTypeTableViewCell {
        let cell = Bundle.main.loadNibNamed("AccountTypeTableViewCell", owner: self, options: nil)?.last
        return cell as! AccountTypeTableViewCell
    }

    override func awakeFromNib() {
        super.awakeFromNib()
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.scrollDirection = .horizontal
        flowLayout.itemSize = CGSize(width: 289, height: 289)
        flowLayout.minimumLineSpacing = 10.0
        self.collectionView.collectionViewLayout = flowLayout

        self.collectionView.dataSource = self
        self.collectionView.delegate = self

        let cellNib = UINib(nibName: "AccountTypeCell", bundle: nil)
        self.collectionView.register(cellNib, forCellWithReuseIdentifier: cellReuseId)
        collectionView.reloadData()
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
    }

    var collectionViewOffset: CGFloat {
        get {
            return collectionView.contentOffset.x
        }

        set {
            collectionView.contentOffset.x = newValue
        }
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let cell = collectionView.cellForItem(at: indexPath) as? AccountTypeCollectionViewCell
        self.cellDelegate?.collectionView(collectioncell: cell, didTappedInTableview: self, collectionRow: indexPath.row)
    }


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

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellReuseId, for: indexPath) as? AccountTypeCollectionViewCell
        cell?.updateCellWithImage(name: "videoCallWaiting")
        setRoundedViewWithBorder(view: (cell?.AccountTypeView)!, borderColor: "999999", bgColor: "FFFFFF")
        cell?.txtAccountTypeDescription.isScrollEnabled = true
        return cell!
    }}

В AccountTypeViewController (просмотр контроллера таблицы) я установил так:

extension AccountTypeViewController:CustomCollectionCellDelegate {
    func OpenNows(wasPressedOnCell cell: AccountTypeCollectionViewCell?) {
        print("hasil nya eh dipencet")
        let accountRegular = Account(accountType: "signUp.accountTypeRegular".localized(), code: AccountType.regular)
        let signUpViewController = SignUpViewController.fromStoryboard(name: AppStoryboard.Signup.instance)
        let signUpViewModel = SignupViewModel.shared
        signUpViewModel.accountType = accountRegular
        signUpViewController.signupViewModel = signUpViewModel
        navigationController?.pushViewController(signUpViewController, animated: true)
    }

    func collectionView(collectioncell: AccountTypeCollectionViewCell?, didTappedInTableview TableCell: AccountTypeTableViewCell, collectionRow: Int) {
        print("collectionRow clicked:\(collectionRow)")
    }
}

Я пытался с delegate2?.navigationController?.pushViewController(signUpViewController, animated: true), он не может pu sh to signUpViewController.

Я также пытался с delegate?.OpenNows(wasPressedOnCell: self) также не могу pu sh подписатьUpViewController.

И я также хочу получить строку tableView внутри ячейки collectionView, как это сделать?

Пожалуйста, помогите мне исправить мой код, чтобы он мог sh подписатьUpViewController и получить строку tableView внутри ячейки collectionView.

1 Ответ

0 голосов
/ 16 января 2020

Вы можете просто передать делегату этот pu sh следующему ViewController между всей этой массой. Выполните эти шаги и попробуйте свой делегат снова, может быть, вы забыли установить во вложенных компонентах ....

// ViewControllerExtension с функциями делегата

extension AccountTypeViewController:CustomCollectionCellDelegate {
    func OpenNows(wasPressedOnCell cell: AccountTypeCollectionViewCell?) {
        print("hasil nya eh dipencet")
        let accountRegular = Account(accountType: "signUp.accountTypeRegular".localized(), code: AccountType.regular)
        let signUpViewController = SignUpViewController.fromStoryboard(name: AppStoryboard.Signup.instance)
        let signUpViewModel = SignupViewModel.shared
        signUpViewModel.accountType = accountRegular
        signUpViewController.signupViewModel = signUpViewModel
        navigationController?.pushViewController(signUpViewController, animated: true)
    }

    func collectionView(collectioncell: AccountTypeCollectionViewCell?, didTappedInTableview TableCell: AccountTypeTableViewCell, collectionRow: Int) {
        print("collectionRow clicked:\(collectionRow)")
    }
}

// ViewController, который устанавливает себя как делегат в ячейках таблицы ...

class AccountTypeViewController: UIViewController {
     //......
     //multiple code
     //......

     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
          //when you dequeue your cell insert the delegate
          // Everything I write next is pseudocode so do not simply copy+paste
          let cell = AccountTypeTableViewCell()
          cell.delegate = self
          return cell
     }

}

// Ячейка таблицы, в которой используется делегат, установленный ViewController внутри вложенной CollectionCells

class AccountTypeTableViewCell: UITableViewCell, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
     weak var cellDelegate: CustomCollectionCellDelegate?

     //......
     //multiple code
     //......

     func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
           //when you dequeue your cell insert the delegate
           // Everything I write next is pseudocode so do not simply copy+paste
           let cell = AccountTypeCollectionViewCell()
           cell.delegate = cellDelegate
           return cell
     }
}

// CollectionCell, которая вызывает делегат функция, вложенная между компонентами

class AccountTypeCollectionViewCell: UICollectionViewCell {
     //......
     //Multiple component
     //......
     weak var delegate: CustomCollectionCellDelegate?

     @IBAction func btnMoreInfoPressed(_ sender: UIButton) {
         print("btnMoreInfoPressed eh dipencet")
         delegate?.OpenNows(wasPressedOnCell: self)
     }
 }

Попробуйте и сделайте свой код проще и понятнее, чтобы упростить ваши будущие настройки :) Скажите, работает ли он

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...