Как открыть навигационный контроллер с выбранным названием ячейки - PullRequest
1 голос
/ 19 апреля 2019

Я бы хотел, чтобы навигационный контроллер открывался при выборе ячейки таблицы.На навигационном контроллере должен быть заголовок текста, выделенного в выбранной ячейке.

Я думаю, что я очень близок со своим кодом, но не могу понять, что я делаю неправильно.

Ничего не открывается, когда я выбираю ячейку из таблицы.

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

        // Retrieve cell
        let cellIdentifier: String = "stockCell"
        let myCell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)!
        myCell.textLabel?.textAlignment = .center
        myCell.textLabel?.font = .boldSystemFont(ofSize: 18)
        // Get the stock to be shown
        let item: StockModel = feedItems[indexPath.row] as! StockModel
        // Configure our cell title made up of name and price


        let titleStr = [item.customer].compactMap { $0 }.joined(separator: "-")


        print(titleStr)
        // Get references to labels of cell
        myCell.textLabel!.text = titleStr

        return myCell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        let item: StockModel = feedItems[indexPath.row] as! StockModel
        let titleStr = [item.customer].compactMap { $0 }.joined(separator: "-")

        print(titleStr)

    }

     func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "customerDetails" {

        let destinationVC = segue.destination as UIViewController
        let cellIdentifier: String = "stockCell"
        let myCell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)!
        destinationVC.navigationItem.title = myCell.textLabel!.text
        }
    }

}

НОВОЕ ОБНОВЛЕНИЕ:

СЛЕДУЮЩАЯ СЕЙЧАС РАБОТАЕТ:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {


    let cellIdentifier: String = "stockCell"
    let myCell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)!
    myCell.textLabel?.textAlignment = .center

    // Get the stock to be shown
    let item: StockModel = feedItems[indexPath.row] as! StockModel
    // Configure our cell title made up of name and price

    let titleStr = [item.customer].compactMap { $0 }.joined(separator: "-")

    print(titleStr)
    // Get references to labels of cell
    myCell.textLabel!.text = titleStr

    let controller = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "detailController")
    controller.title = titleStr
    navigationController?.pushViewController(controller, animated: true)

}

Но мне нужно, чтобы контроллер представления представлял собой стиль раскадровки Show Detail, где detailController накладывается на FirstViewController.

Куда вы не можете вернуться назад.

Ответы [ 4 ]

1 голос
/ 19 апреля 2019

сделайте это в вашей версии обновления

let controller = storyboard.instantiateviewcontroller(withIdentifier: "youridentifier") as? "name of your view controller"
navigationController?.present(controller, animated: true, completion: nil)
1 голос
/ 19 апреля 2019

В этом случае лучше всего просто нажать контроллер вида программно. Очень простой полный пример будет выглядеть следующим образом:

class ViewController: UIViewController {

    let titles: [String] = ["First", "Second", "Third"]

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

}

// MARK: - UITableViewDelegate, UITableViewDataSource

extension ViewController: UITableViewDelegate, UITableViewDataSource {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return titles.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .default, reuseIdentifier: nil)
        cell.textLabel?.text = titles[indexPath.row]
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let controller = UIViewController() // or UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "whateverIdentifierISetInStoryboard")
        controller.title = titles[indexPath.row]
        navigationController?.pushViewController(controller, animated: true)
    }

}

Таким образом, использование navigationController?.pushViewController(controller, animated: true) - это метод, который покажет новый контроллер представления с анимацией справа налево.

Заголовок просто устанавливается непосредственно на контроллере вида, который можно создать из раскадровки с помощью UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "whateverIdentifierISetInStoryboard").

Предполагается, что этот контроллер вида уже находится на контроллере навигации.

Если вам действительно нужно сделать это с segues, тогда вам нужно вручную вызвать segue с использованием идентификаторов. Вы также отправляете свой заголовок как параметр sender.

self.performSegue(withIdentifier: "customerDetails", sender: titles[indexPath.row])

В вашем случае, вероятно, что-то вроде:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let item: StockModel = feedItems[indexPath.row] as! StockModel
    let titleStr = [item.customer].compactMap { $0 }.joined(separator: "-")
    self.performSegue(withIdentifier: "customerDetails", sender: titleStr)
}

Теперь просто используйте этот заголовок:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "customerDetails" {
        let destinationVC = segue.destination as UIViewController
        destinationVC.title = sender as? String
    }
}

Другой подход - сохранить текущий заголовок свойства, а затем использовать его при подготовке segue:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let item: StockModel = feedItems[indexPath.row] as! StockModel
    let titleStr = [item.customer].compactMap { $0 }.joined(separator: "-")
    self.nextScreenTitle = titleStr
    self.performSegue(withIdentifier: "customerDetails", sender: self)
}

А потом использование:

var nextScreenTitle: String?
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "customerDetails" {
        let destinationVC = segue.destination as UIViewController
        destinationVC.title = nextScreenTitle
    }
}
1 голос
/ 19 апреля 2019

Вы должны использовать переменную в deistinationVC , затем в ViewDidLoad использовать "navigationItem.title"

In firstViewController :

func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "customerDetails" {

    let destinationVC = segue.destination as UIViewController
    let cellIdentifier: String = "stockCell"
    let myCell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)!
    destinationVC.navTitle = myCell.textLabel!.text
    }
}

И SecondViewController :

class secondViewcontroller : UIViewController{

  var navTitle = string()

  override func viewDidLoad() {

    navigationItem.title = navTitle

   }
1 голос
/ 19 апреля 2019

Проверьте, подключен ли segue в файле main.storyboard.Если это так, проверьте, совпадает ли идентификатор с кодом.Если это не сработает, это может быть потому, что вы создаете новую ячейку в prepareForSegue и исправляете необходимость создания глобальной переменной для каждой ячейки.Если все это не работает, скажите мне.Можете ли вы прикрепить файл main.storyboard.

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