Swift UITableView didSelectRowAtIndexPath не получает вызов

Новое для разработки IOS, и у меня возникают проблемы с обработкой выбора ячеек таблицы. Всякий раз, когда я выбираю, метод не называется ниже - любая идея почему?

Моя структура проекта: View Controller → Вид → Просмотр таблицы

В приведенном ниже коде демонстрируются вызовы методов. Другие вызываются без проблем! Я знаю, что прикосновение работает, когда сбрасывание успешно обновляется и при нажатии на ячейку оно становится выделенным.

import UIKit

class ViewController: UIViewController, UITableViewDelegate
{

   let blah = ["blah1"]

   //How many sections are in the table?
   func numberOfSectionsInTableView(tableView: UITableView) -> Int {
      return 1
   }

   //How many rows? (returns and int)
   func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
      return blah.count
   }

  //table contents for each cell?
  //Each time this is called it'll return the next row and thus build a table...
  func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
      print("Populating each cell of table view!\n")
      tableView.rowHeight = 80.0
      var cell = UITableViewCell()

      var(a) = blah[indexPath.row]
      var image : UIImage = UIImage(named: a)!
      cell.imageView.image = image

      return cell
  }



  //Code Cell Selected
  func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
      println("You selected cell #\(indexPath.row)!")

  }


  func tableView(tableView: UITableViewDelegate, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
     print("wananananaanan" )
     println("You deselected cell #\(indexPath.row)!")

  }




  override func viewDidLoad() {
     super.viewDidLoad()

     // Do any additional setup after loading the view, typically from a nib.

  }

  override func didReceiveMemoryWarning() {
     super.didReceiveMemoryWarning()
     // Dispose of any resources that can be recreated.
  }
}

Ответы

Ответ 1

Вы должны установить @IBOutlet в tableView в ViewController и установить как delegate и dataSource, чтобы вы могли видеть данные, реагирующие на изменения в tableView.

Что-то вроде этого:

override func viewDidLoad() {
    super.viewDidLoad()

    self.tableView.delegate = self
    self.tableView.dataSource = self
}

И также реализует протокол UITableViewDataSource.

Или вы тоже можете в построителе интерфейса установить ViewController, как он делегировать, и dataSource (что проще сделать, я думаю) и не устанавливать вручную в коде, как описано выше. Это зависит от вас.

Надеюсь, это поможет вам.

Ответ 2

Все упоминают, чтобы установить dataSource и удалить tableView. Но после настройки также не работает нормально, иногда это может произойти из-за отсутствия или отключить выбор табличного представления.

Чтобы включить его, перейдите в раскадровку → выберите tableView → щелкните инспектор атрибута → перейдите к селектору → выберите выбор как одиночный выбор (или множественный выбор в соответствии с требованиями). Please find attachment

Пожалуйста, найдите прикрепленный скриншот для вашей пригодности.

Ответ 3

SWIFT 3

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
      // Do here
    }

Используйте вышеуказанный метод делегата в swift 3

Ответ 4

Я столкнулся с той же проблемой, когда сравнивал два идентичных примера кода, где один работал хорошо, а другой не вызывал didSelectRowAtIndexPath

Взгляните на два возможных способа решения проблемы:

1) В самом коде:

@IBOutlet weak var table: UITableView!

override func viewDidLoad() {
    table.delegate = self
    table.dataSource = self 
//data source might be already set if you see contents of the cells
//the main trick is to set delegate
}

2) Использование Storyboard или Document Outline (что было проблемой в моем случае, причиной изменения раскадровки не видно в классах контроллера .swift.

Откройте "Структура документа" и Control + Press ваш TableView вы увидите два выхода под названием "delegate" и "dataSource", перетащите их 1 на 1 в содержащий ViewController (прямо на желтый круг)

Что это!

Ответ 5

  • Пара проверок, которые могут помочь вам:

    myTableView.allowsSelection = true

    myTableView.delegate = self

  • Убедитесь, что вы написали didSelectRowAt правильно:

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

  • Если вы используете UIButton для UITableViewCell тогда он перекрывает ячейку, поэтому проверьте решение здесь

Ответ 6

Вы должны использовать это: сначала посмотрите, что вы расширяете, а затем используйте метод tableView.

    class YourViewController : UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var mUITableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // We need to tell to UITableView that we will add the data by ourselves
        self.mUITableView.delegate = self
        self.mUITableView.dataSource = self

        // Register the UITableViewCell class with the tableView
        self.mUITableView?.registerClass(UITableViewCell.self, forCellReuseIdentifier: self.cellIdentifier)
        // Setup table data
        getEvents()

        self.mUITableView.allowsSelection = true   
    }

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

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
       //  here to create you cell view      
    }

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        print("You selected cell #\(indexPath.row)!")
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "subtitleCell")
        cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
        cell.textLabel?.text = "\(tableData[indexPath.row].name) - (\(tableData[indexPath.row].eventStateId))"
        cell.detailTextLabel?.text = tableData[indexPath.row].lastUpdate
        return cell
    }
}

Ответ 7

Еще одна причина, по которой вы можете написать эту функцию, которая позволяет нажимать при условии

func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool {
    if(indexPath.section == 1){
        return true
    }
    return false
}

Ответ 8

Еще одно предостережение, которое потребовалось мне для выяснения возраста, - убедиться, что все три в вашем табличном представлении, ячейке и представлении содержимого имеют взаимодействие с пользователем. Тогда в Swift 4, по крайней мере, вы можете использовать:

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