didselectrowatindexpath текстовая метка возврат - PullRequest
0 голосов
/ 30 мая 2018

Я пытаюсь вернуть значение titleField или заголовка из ячейки, которая была нажата.После небольшой копки я нашел некоторый код, который должен работать, но я получаю ошибку:

Значение типа 'UITableViewCell' не имеет члена 'titleField'

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

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let cell = tableView.dequeueReusableCell(withIdentifier:"searchCell", for: indexPath)
        as! CustomTableViewCell
        cell.titleField?.text = posts[indexPath.row].caption
        cell.descriptionField?.text = posts[indexPath.row].description
        cell.tagsField?.text = posts[indexPath.row].tags
        let photoUrl = posts[indexPath.row].photoUrl
        let url = URL(string: photoUrl)
        cell.SearchImage.sd_setImage(with: url, placeholderImage: nil)
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let indexPath = tableView.indexPathForSelectedRow

        //getting the current cell from the index path
        let currentCell = tableView.cellForRow(at: indexPath!)! as UITableViewCell

        //getting the text of that cell
        let currentItem = currentCell.titleField!.text //HERE IS THE ERROR!
    }
}

Ответы [ 3 ]

0 голосов
/ 30 мая 2018

Никогда не используйте ячейку для получения данных.Получите ваши данные из вашей модели данных точно так же, как вы это делаете в cellForRowAt.

И didSelectRowAt предоставляет индексный путь только что выбранной строки.

Обновите didSelectRowAt дочто-то вроде:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let caption = posts[indexPath.row].caption
    let tags = posts[indexPath.row].tags
}
0 голосов
/ 30 мая 2018

Да, вы разыгрываете ячейку в didSelectRow в UITableViewCell, а не CustomTableViewCell.Другой момент заключается в том, что вы можете использовать indexPath напрямую.Нет необходимости в let indexPath = tableView.indexPathForSelectedRow.

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

    let currentCell = tableView.cellForRow(at: indexPath)! as CustomTableViewCell

    //getting the text of that cell
    let currentItem = currentCell.titleField!.text
}
0 голосов
/ 30 мая 2018

Проблема в том, что вы инициализируете ячейку как UITableViewCell в методе DidSelectRow.Просто измените его на CustomTableViewCell

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

    // getting the current cell from the index path
    let currentCell = tableView.cellForRow(at: indexPath!)! as CustomTableViewCell     // THE SOLUTION

    // getting the text of that cell
    let currentItem = currentCell.titleField!.text 
}

или вы также можете использовать массив данных для получения значения метки с помощью indexPath

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