Как открыть View Controller в табличном представлении с помощью кнопки, используя Obj c в Swift? - PullRequest
3 голосов
/ 18 января 2020

Stackoverflow

Я знаю, как сделать кнопку в ячейках табличного представления со ссылками на сайт, тарифами, почтой и многими другими вещами. Однако, как я могу открыть контроллер представления с instantiateViewController в операторах @Objc fun c?

Например.

Создать новую папку ячейки табличного представления с именем FeedBackButtonsTableViewCell

class FeedBackButtonsTableViewCell: UITableViewCell {

    @IBOutlet weak var ButtonCells: UIButton!

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

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

        // Configure the view for the selected state
    }

}

Позвольте создать новую папку контроллера представления с именем

class FeedbackViewController: UIViewController {


       @IBOutlet weak var TableView: UITableView!


    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.

          self.navigationItem.title = "Feedback"
    }

}

добавить расширение для вызова контроллера представления в UITableViewDataSource и UITableViewDelegate и создать obj fun c операторы внутри второго FeedbackViewController с UITableViewDataSource и UITableViewDelegate под ячейками.

extension FeedbackViewController: UITableViewDataSource, UITableViewDelegate {

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

        return 1
    }

     if indexPath.row == 1 {

            buttonCell = TableView.dequeueReusableCell(withIdentifier: "ButtonCells") as? FeedBackButtonsTableViewCell

             buttonCell?.ButtonCells.addTarget(self,action: #selector(LearnMore),for: .touchUpInside)

             buttonCell?.ButtonCells.tag = indexPath.row

             return buttonCell!

        }

  @objc func LearnMore() {

    // How could I write to open the view controller with UIButton in the Table View Cells?

  }
}

Спасибо за помощь! :)

Ответы [ 2 ]

4 голосов
/ 18 января 2020

Простым решением может быть использование procol.


protocol CellActionDelegate{
    func didButtonTapped(index: Int)
}

Теперь подтвердите протокол в FeedbackViewController. Возьмите index и actionDelegate свойства в вашем подклассе UITableViewCell.

class FeedBackButtonsTableViewCell: UITableViewCell{

    var actionDelegate: CellActionDelegate?
    var index: Int?

    .....



    // Take Action of UIButton here

    @IBAction func more(_ sender: Any) {
      if let delegate = self.actionDelegate{

        delegate.didButtonTapped(index!)
      }
    }


}

Теперь в вашем FeedbackViewController наборе actionDelegate & Соответствующий индекс в

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {}

вы можете открыть другой контроллер ViewView из func didButtonTapped(index: Int) определение.

extension FeedbackViewController:CellActionDelegate{
 func didButtonTapped(index: Int) {
        let storybord = UIStoryboard(name: "Main", bundle: nil)
        guard let controller = storybord.instantiateViewController(withIdentifier: "AnotherControllerIdentfier") as? AnotherViewController else{
            fatalError("Could not finc another view controller")
        }
        self.present(controller, animated: true, completion: nil)
    }
}
0 голосов
/ 18 января 2020

    @objc func LearnMore() {

        let viewController = FeedbackDetailsViewController()// creation of viewController object differs depends on how you fetch the UI, means either you are using storyboard or xib or directly making ui in code.
        self.navigationController?.pushViewController(viewController, animated: true)

      }

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