Получение данных текстового поля из пользовательской ячейки из другого представления вне табличного представления - PullRequest
1 голос
/ 21 апреля 2020

У меня есть представление со встроенным UITableViewController, который заполнен пользовательскими ячейками. Когда я нажимаю кнопку «Сохранить», я бы хотел, чтобы getProjectName () внутри UITableViewController возвращал данные projectNameTF внутри пользовательской ячейки. В настоящее время, когда я пытаюсь получить ячейку внутри getProjectName (), она возвращает нулевую ячейку.

Главный вид:

class NewProjectView: UIViewController {

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

    @IBAction func saveBtn(_ sender: UIButton) {
        print("Save button hit")
        print(NewProjectTableViewController().getProjectName())
    }

}

Встроенный TableViewController

import UIKit

struct cellType{
    var mainTitle = String()
    var numOfChildCells = Int()
    var opened = Bool()
}

class NewProjectTableViewController: UITableViewController {

    var tableViewData = [cellType]()
    var customCellData = [UITableViewCell]()

    var projectNameTFR = UITextField()



    // Counts the number of cells and displays them
    override func numberOfSections(in tableView: UITableView) -> Int {
        return tableViewData.count
    }

    override func  tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        // If the parent cell is opened display the number of cells inside it
        if tableViewData[section].opened == true {
            return tableViewData[section].numOfChildCells + 1
        }

        else {
            return 1
        }
    }

    //
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        self.tableView.separatorStyle = .none

        // Do this for the header cell
        if indexPath.row == 0{

            guard let cell = tableView.dequeueReusableCell(withIdentifier: "HeaderCell") as? HeaderCell else {return UITableViewCell()}

            cell.backgroundColor = .clear
            cell.setUpCell(title: tableViewData[indexPath.section].mainTitle)

            // If cell should be opened, display correct open image
            if tableViewData[indexPath.section].opened{
                cell.openCell()
            }

            // else display closed image
            else{
                cell.closeCell()
            }

            return cell

        // else it is a child cell
        }else {

            switch tableViewData[indexPath.section].mainTitle{

                // Load Project info cell
                case "Project Information":
                    guard let cell = tableView.dequeueReusableCell(withIdentifier: "ProjectNameCell") as? ProjectNameCell else {return UITableViewCell()}
                    projectNameTFR = cell.projectNameTF
                    return cell

                case "Client Information":
                    guard let cell = tableView.dequeueReusableCell(withIdentifier: "ClientInfoCell") as? ClientInfoCell else {return UITableViewCell()}
                    return cell

                default:
                    print("defaulted cell")
                    guard let cell = tableView.dequeueReusableCell(withIdentifier: "cell") else {return UITableViewCell()}
                    return cell
            }

        }
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if tableViewData[indexPath.section].opened == true{
            tableViewData[indexPath.section].opened = false
            let sections = IndexSet.init(integer: indexPath.section)
            tableView.reloadSections(sections, with: .none)
            let headerCell = tableView.cellForRow(at: indexPath) as! HeaderCell


        }
        else{
            tableViewData[indexPath.section].opened = true
            let sections = IndexSet.init(integer: indexPath.section)
            tableView.reloadSections(sections, with: .none)
            let headerCell = tableView.cellForRow(at: indexPath) as! HeaderCell
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        //self.definesPresentationContext = true
        tableView.delegate = self
        tableView.dataSource = self

        tableView.rowHeight = UITableView.automaticDimension

        // Do any additional setup after loading the view.
        print("add new client screen loaded")

        registerTableViewCells()

        // Create the cells
        tableViewData = [cellType(mainTitle: "Project Information", numOfChildCells: 1, opened: true ),
                         cellType(mainTitle: "Client Information", numOfChildCells: 1, opened: false )]

    }

    override func viewWillAppear(_ animated: Bool) {
        // Add a background view to the table view
        let backgroundImage = UIImage(named: "App Background.png")
        let imageView = UIImageView(image: backgroundImage)
        self.tableView.backgroundView = imageView
    }


    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }

    private func registerTableViewCells(){
        let ClientInfoCell = UINib(nibName: "ClientInfoCell", bundle: nil)
        self.tableView.register(ClientInfoCell, forCellReuseIdentifier: "ClientInfoCell")

        let ProjectNameCell = UINib(nibName: "ProjectNameCell", bundle: nil)
        self.tableView.register(ProjectNameCell, forCellReuseIdentifier: "ProjectNameCell")

        let HeaderCell = UINib(nibName: "HeaderCell", bundle: nil)
        self.tableView.register(HeaderCell, forCellReuseIdentifier: "HeaderCell")

        let SaveCell = UINib(nibName: "SaveCell", bundle: nil)
        self.tableView.register(SaveCell, forCellReuseIdentifier: "SaveCell")

    }

    func getProjectName() -> String{

        let indexPath = NSIndexPath(row: 0, section: 0)
        let cell = tableView?.cellForRow(at: indexPath as IndexPath) as? ProjectNameCell
        print(type(of: cell))

        if(cell==nil){
            print("cell is nil")
        }

        return "I returned this test string"
    }
}

Пользовательская ячейка Я пытаюсь связаться

import UIKit

class ProjectNameCell: UITableViewCell {

    @IBOutlet weak var projectNameTF: UITextField!

    var projectName = String()

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
        backgroundColor = .clear

    }

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

        // Configure the view for the selected state
    }


}

1 Ответ

2 голосов
/ 21 апреля 2020

Хорошо, сэр, вы получаете ячейку на пути индекса 0, номер раздела и 0-ую строку

let indexPath = NSIndexPath(row: 0, section: 0)

для этого индекса у вас есть HeaderCell вместо ProjectNameCell, поэтому вы получаете nil

эта линия не может привести ваш HeaderCell к ProjectNameCell

let cell = tableView?.cellForRow(at: indexPath as IndexPath) as? ProjectNameCell
...