Подтвердить что ты не робот

Как обнаружить клетку tableView, затронутую или щелкнув в быстрой

Я пытаюсь получить index выбранного элемента в TableView и начать с него некоторые действия. К сожалению, большинство решений, которые я нашел, находятся в objective-c или не работают.

Метод func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) не печатает метку cell.

Может кто-нибудь мне помочь?

import UIKit
import ResearchKit

class TaskListViewController: UIViewController, UITableViewDataSource {

    let tasks=[("Short walk"),
        ("Audiometry"),
        ("Finger tapping"),
        ("Reaction time"),
        ("Spatial span memory")
    ]


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

    //return int how many rows
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return tasks.count
    }

    //what are the contents

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell = UITableViewCell()

        var (testName) = tasks[indexPath.row]
        cell.textLabel?.text=testName
        return cell
    }

    // give each table section a name

    func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {

        return "Tasks"

    }

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

        let indexPath = tableView.indexPathForSelectedRow();

        let currentCell = tableView.cellForRowAtIndexPath(indexPath!) as UITableViewCell!

        println(currentCell.textLabel!.text)
    }


    override func viewDidLoad() {
        super.viewDidLoad()

    }  
}

После нескольких попыток я изменил код на другой из учебника, который я нашел. И это тоже не работает. Теперь я думаю, что это проблема с симулятором iOS...

import UIKit
import ResearchKit

class TaskListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet
    var tableView: UITableView?
    var items: [String] = ["We", "Heart", "Swift"]

    override func viewDidLoad() {
        super.viewDidLoad()

        self.tableView!.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
    }


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

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell:UITableViewCell = self.tableView!.dequeueReusableCellWithIdentifier("cell") as! UITableViewCell

        cell.textLabel?.text = self.items[indexPath.row]

        return cell
    }

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

}

4b9b3361

Ответ 1

Если вы хотите получить значение из ячейки, вам не нужно воссоздавать ячейку в didSelectRowAtIndexPath

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    println(tasks[indexPath.row])
}

Задача следующая:

let tasks=["Short walk",
    "Audiometry",
    "Finger tapping",
    "Reaction time",
    "Spatial span memory"
]

также вы должны проверить cellForRowAtIndexPath, что вы должны установить идентификатор.

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("CellIdentifier", forIndexPath: indexPath) as UITableViewCell
    var (testName) = tasks[indexPath.row]
    cell.textLabel?.text=testName
    return cell
}

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

Ответ 2

В Swift 3.0

Вы можете найти событие для касания/щелчка ячейки таблицы view через метод делегирования. Кроме того, можно найти значение раздела и строки ячейки, как это.

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
       print("section: \(indexPath.section)")
       print("row: \(indexPath.row)")
}

Ответ 3

Проблема была решена мной самостоятельно с помощью учебника weheartswift

enter image description here

Ответ 4

Несколько вещей, которые должны произойти...

  1. Контроллер представления должен расширять тип UITableViewDelegate

  2. Контроллер представления должен включать функцию didSelectRowAt.

  3. Табличному представлению должен быть назначен контроллер представления в качестве его делегата.


Ниже приведено одно место, где может происходить назначение делегата (в контроллере представления).

override func loadView() {
    tableView.dataSource = self
    tableView.delegate = self
    view = tableView
}

И простая реализация функции didSelectRowAt.

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    print("row: \(indexPath.row)")
}

Ответ 5

Это сработало для меня:

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("section: \(indexPath.section)")
        print("row: \(indexPath.row)")
    }

Ответ 6

Унаследуйте делегат tableview и источник данных. Реализуйте делегатов, что вам нужно.

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

И, наконец, реализовать этот делегат

     func tableView(_ tableView: UITableView, didSelectRowAt  
     indexPath: IndexPath) {
     print("row selected : \(indexPath.row)")
  }

Ответ 7

Чтобы получить элементы из массива в ячейке tableView, коснулись или щелкнули в Swift

func tableView(_ tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("CellIdentifier", forIndexPath: indexPath) as UITableViewCell
    cell.textLabel?.text= arr_AsianCountries[indexPath.row]
    return cell
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let indexpath = arr_AsianCountries[indexPath.row]
print("indexpath:\(indexpath)")
}

Ответ 8

 # Check delegate? first must be connected owner of view controller

    # Simple implementation of the didSelectRowAt function.

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
         print("row selection: \(indexPath.row)")
    }

Ответ 9

Я облажался каждый раз! Просто убедитесь, что tableView делегат и dataSource объявлены в viewDidLoad. Затем я обычно заполняю несколько массивов для имитации возвращаемых данных, а затем беру их оттуда!

//******** Populate Table with data ***********
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{

    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as? SetupCellView
    cell?.ControllerLbl.text = ViewContHeading[indexPath.row]
    cell?.DetailLbl.text = ViewContDetail[indexPath.row]
    cell?.StartupImageImg.image = UIImage(named: ViewContImages[indexPath.row])
    return cell!
}