Уволить UIViewController для TableViewCell - PullRequest
1 голос
/ 17 мая 2019

У меня есть табличное представление внутри UIViewController. Это табличное представление имеет динамическую таблицу с кнопками.

Я установил функцию для каждой кнопки внутри TableViewCell следующим образом:

class ButtonTableViewCell: UITableViewCell {

    let defaults = UserDefaults.standard
    var targetTitle: String!

    @IBOutlet weak var buttonDisplay: UIButton!

    func setButton(title: String) {
        buttonDisplay.setTitle(title.uppercased(), for: .normal)
        targetTitle = title
        buttonDisplay.addTarget(self, action: #selector(changeValue(_:)), for: .touchUpInside)
    }

    @objc func changeValue(_ sender: Any) {
        currentCar = targetTitle
        defaults.set(currentCar, forKey: "currentCar")
    }

}

Как я могу закрыть UIViewController, который содержит TableView внутри функции @objc func changeValue(_ sender: Any)?

Кроме того, поскольку кнопки добавляются динамически, мне также нужна динамическая высота для самого табличного представления - как я могу настроить табличное представление для каждой добавленной ячейки?

UIViewController:

class DropdownViewController: UIViewController {

    @IBOutlet weak var tableViewButtons: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        tableViewButtons.delegate = self
        tableViewButtons.dataSource = self
    }

}

extension DropdownViewController: UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return carsArray.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let rowData = carsArray[indexPath.row]

        let cell = tableView.dequeueReusableCell(withIdentifier: "buttonCell") as! ButtonTableViewCell
        cell.setButton(title: rowData.name)
        return cell
    }
}

Ответы [ 2 ]

1 голос
/ 17 мая 2019

Вы можете использовать делегатов:

protocol ButtonTableViewCellDelegate {
   func dismissFromCell()
}

class ButtonTableViewCell: UITableViewCell {

    let defaults = UserDefaults.standard
    var targetTitle: String!

    // Delegate should be weak to avoid memory leaks
    weak var delegate: ButtonTableViewCellDelegate?

    @IBOutlet weak var buttonDisplay: UIButton!

    func setButton(title: String) {
        buttonDisplay.setTitle(title.uppercased(), for: .normal)
        targetTitle = title
        buttonDisplay.addTarget(self, action: #selector(changeValue(_:)), for: .touchUpInside)
    }

    @objc func changeValue(_ sender: Any) {
        currentCar = targetTitle
        defaults.set(currentCar, forKey: "currentCar")
        delegate?.dismissFromCell()
    }
}

class DropdownViewController: UIViewController {

    @IBOutlet weak var tableViewButtons: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        tableViewButtons.delegate = self
        tableViewButtons.dataSource = self
    }

}

extension DropdownViewController: UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return carsArray.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let rowData = carsArray[indexPath.row]

        let cell = tableView.dequeueReusableCell(withIdentifier: "buttonCell") as! ButtonTableViewCell
        cell.setButton(title: rowData.name)
        // Setting Delegate here
        cell.delegate = self
        return cell
    }
}

// Extend your controller to conform your Delegate Protocol
extension DropdownViewController: ButtonTableViewCellDelegate {
   func dismissFromCell() {
       self.dismiss()
   }
}

Подробнее о схеме делегирования вы можете узнать здесь: https://www.appcoda.com/swift-delegate/

0 голосов
/ 17 мая 2019

Вы захотите использовать делегата для выполнения действия. Просто создайте протокол с функцией и вызовите делегата в вашей функции changeValue.

В противном случае используйте это:

var responder: UIResponder! = self
repeat { responder = responder.next } while !(responder is UIViewController)
(responder as! UIViewController).dismiss()

Он просто идет вверх по цепочке респондента, пока не находит UIViewController, а затем выполняет любое необходимое действие. Используйте это, только если у вас есть UIViewController в качестве родителя, иначе это не будет работать.

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