2015-03-15 5 views
16

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

Моя структура проекта: 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. 
    } 
} 
+2

вы поставили перед собой как вид таблиц делегировать? –

ответ

28

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

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

override func viewDidLoad() { 
    super.viewDidLoad() 

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

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

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

Я надеюсь, что это поможет вам.

+0

Или вместо подкласса 'UIViewController', используйте' UITableViewController' - тогда вы получаете множество функций бесплатно. Например, 'UITableView' будет уже настроен для вас с делегатами, указывающими на ваш контроллер представления. –

+0

Да, конечно, комментарий @Stefan тоже действителен! –

+0

Спасибо, что сработало отлично! (Я пошел с быстрым вариантом установки контроллера просмотра в качестве выходного отверстия делегата. – Mark

5

я столкнулся с той же проблемой при сравнении двух одинаковых примеров кода, где один работает хорошо, а другой не призывающих 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) Использование раскадровки или структуры документа (который был проблема в моем случае вызывают изменения раскадровки не видны в .swift классов контроллеров

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

Вот оно!

1

Вы должны использовать это: сначала посмотрите, что вы расширяете, а затем используйте метод 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 
    } 



} 
15

СВИФТ 3

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

Используйте выше метод делегата в быстром 3

+0

только это решение работало здесь даже через несколько часов в поисках решения. спасибо – guijob

+0

add override, а также – Stingalingaling

Смежные вопросы