как вызвать popviewcontroller в UITableViewCell - PullRequest
0 голосов
/ 29 июня 2018

Текущая структура

firstViewController -> pushViewController (SecondViewController)

-UIViewController      ->filename :  secondViewController

    -UITableView        


        -UITableViewCell (custom cell)     ->filename :  secondTableViewCell

            -UICollectionView                


                -UICollectionViewCell (custom cell)      ->filename : secondCollectionViewCell

Когда «didSelectItemAt» выполняется в «UICollectionView»

Я бы хотел вызвать 'popviewcontroller' из UIViewController.

И я хочу передать данные о выбранном элементе в firstViewController.

но я не знаю как

** ViewController **

struct cellStat{
var opened = Bool()
var title = String()
var sectionData = [ItemModel]()
}

//선물 카테고리 리스트 보여주는 모달
class GiftCategoryModalVC: UIViewController {

@IBOutlet weak var tableView: UITableView!

private var categoryTitleModels: [ItemModel] = []
private var giftItemModels: [ItemModel] = []
private var titleCellData: [cellStat] = []

//LIFE CYCLE
override func viewDidLoad() {
    super.viewDidLoad()

    tableView.delegate = self
    tableView.dataSource = self
    tableView.register(UINib(nibName: GiftCategoryTBCell.reusableIdentifier, bundle: nil), forCellReuseIdentifier: GiftCategoryTBCell.reusableIdentifier)
    tableView.register(UINib(nibName: GiftCategoryListTBCell.reusableIdentifier, bundle: nil), forCellReuseIdentifier: GiftCategoryListTBCell.reusableIdentifier)

    //get gift categofy title
    GiftPageAPIService.shared.selectCode(code: "CD005") { (itemModels) in
        self.categoryTitleModels = itemModels
        itemModels.forEach { (itemModel) in
            self.titleCellData.append(cellStat(opened: false, title: itemModel.codeNm!, sectionData: []))
        }
        self.tableView.reloadData()
    }
    setupLayout()
}

//LAYOUT
fileprivate func setupLayout(){
    setNavbar()
}

fileprivate func setNavbar(){
    self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "icon_arrow_left"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(handleEndButton))
    self.navigationController?.navigationBar.barTintColor = UIColor.init(hex: 0xececec)
    self.navigationController?.navigationBar.tintColor = UIColor.init(hex: 0x979797)
}


//MAKR:- ACTION
@objc func handleEndButton(){
    self.navigationController?.popViewController(animated: true)
}

}




extension GiftCategoryModalVC: UITableViewDelegate, UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if titleCellData[section].opened == true{
        return 2
    }else{
        return 1
    }
}

func numberOfSections(in tableView: UITableView) -> Int {
    return titleCellData.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if indexPath.row == 0{
        let cell = tableView.dequeueReusableCell(withIdentifier: GiftCategoryTBCell.reusableIdentifier, for: indexPath) as! GiftCategoryTBCell
        cell.setCategotyNm = categoryTitleModels[indexPath.section].codeNm

        if titleCellData[indexPath.section].opened == true{
            cell.setImgView = UIImage(named: "arrow_up")
        }else{
            cell.setImgView = UIImage(named: "arrow_down")
        }
        return cell
    }else{
//this cell is call tableCell
        let cell = tableView.dequeueReusableCell(withIdentifier: GiftCategoryListTBCell.reusableIdentifier, for: indexPath) as! GiftCategoryListTBCell
        cell.setItems = titleCellData[indexPath.section].sectionData

        return cell
    }
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if indexPath.row == 0{
        if titleCellData[indexPath.section].opened == true{
            titleCellData[indexPath.section].opened = false
            let sections = IndexSet.init(integer: indexPath.section)
            tableView.reloadSections(sections, with: .automatic)
        }else{
            titleCellData[indexPath.section].opened = true
            GiftPageAPIService.shared.selectCode(code: categoryTitleModels[indexPath.section].codeCd!) { (items) in

                self.titleCellData[indexPath.section].sectionData = items
                let sections = IndexSet.init(integer: indexPath.section)
                tableView.reloadSections(sections, with: .automatic)
            }
        }
    }
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    if indexPath.row == 0{
        return 50
    }else{
        let cellHeight: Int = (titleCellData[indexPath.section].sectionData.count + 2) / 3
        return self.view.frame.height * 0.24 * CGFloat(cellHeight)
    }
}
}

** TableViewCell **

class GiftCategoryListTBCell: UITableViewCell {

@IBOutlet weak var collectionView: UICollectionView!
var items: [ItemModel]?
var category: ItemModel?

var setCategory: ItemModel?{
    didSet{
        self.category = setCategory!
        getCategoryData()
    }
}

var setItems: [ItemModel]?{
    didSet{
        self.items = setItems!
        collectionView.reloadData()
    }
}


let flowlayout = UICollectionViewFlowLayout()
override func awakeFromNib() {
    super.awakeFromNib()

    collectionView.delegate = self
    collectionView.dataSource = self
    collectionView.register(UINib(nibName: GiftItemCVCell.reusableIdentifier, bundle: nil), forCellWithReuseIdentifier: GiftItemCVCell.reusableIdentifier)

    setupLayout()

}

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

//MARK:- LAYOUT
fileprivate func setupLayout(){
    collectionView.backgroundColor = UIColor.init(hex: 0xf7f7f7)
    collectionView.isScrollEnabled = false
}

fileprivate func getCategoryData(){
    GiftPageAPIService.shared.selectCode(code: (category?.codeCd)!) { (items) in
        self.items = items
        self.collectionView.reloadData()
    }
}

}


extension GiftCategoryListTBCell: UICollectionViewDataSource,UICollectionViewDelegate{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    if items == nil{
        return 0
    }else{
        return (items?.count)!
    }
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: GiftItemCVCell.reusableIdentifier, for: indexPath) as! GiftItemCVCell
    cell.setItem = items?[indexPath.item]
    return cell
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    /*

        I tried to do the work here.

    */
}
}


extension GiftCategoryListTBCell: UICollectionViewDelegateFlowLayout{
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
    return UIEdgeInsets(top: contentView.frame.width * 0.07, left: contentView.frame.width * 0.07, bottom: contentView.frame.width * 0.07, right: contentView.frame.width * 0.07)
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return contentView.frame.width * 0.03
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let width = (contentView.frame.width) * 0.25
    return CGSize(width: width, height: width * 1.5)
}

}

Ответы [ 3 ]

0 голосов
/ 29 июня 2018

Я понимаю, что вы имеете в виду.

Если вы хотите перенести ваш контроллер на предыдущий контроллер в tablecell просто для того, чтобы получить его viewcontroller, который контролирует ячейку, и попытаться выскочить, и если вы попробуете этот метод, почему бы не переопределить делегировать func в вашем viewcontroller? Может быть, немного сложно читать код, но полезно, и вы можете использовать

self.navigationcontroller?.popViewController

Если вы уже использовали viewcontroller для делегирования другого табличного представления, просто оцените имя табличного представления в вашей функции делегата

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
     if tableView == blah blah 
     {
           do what you want
     }
}

И если вам нужно передать данные между различными viewController, особенно передать данные в pre-viewController, вам нужно написать делегат или __block callback.

0 голосов
/ 29 июня 2018

попробуйте это:

let window = UIApplication.shared.keyWindow

window?.topMostWindowController?.navigationController?.popViewController(animated: true)
0 голосов
/ 29 июня 2018

Ты имеешь в виду что-то подобное?

Создать протокол в файле ячейки таблицы

class myTableCell: UITableViewCell{
    var myString = "mystring"
    var delegate = myNewDelegate?

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        delegate?.didSelect(text: self.myString)
    } 

}


protocol myNewDelegate {
   func didSelect(text: String)
}

Это относится к классу контроллера представления, в котором находится ячейка таблицы.

class MyTableViewController: UITableViewController, myNewDelegate{

    var stringToPass = String()

    func didSelectText(text: String){
        stringToPass = text
        self.performSegue(withIdentifier: "editProfileSegue", sender: self)
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
      if segue.identifier == "editProfileSegue"{
         let viewcontroller = segue.destination as! FirstViewController

         viewcontroller.myPassedString = self.stringToPass

        }
    }
}

И затем идентификатор получающего класса

class FirstViewController: UIViewController{
    var myPassedString = String()
}
...