【问题标题】:Swift UITableView didSelectRowAtIndexPath not getting calledSwift UITableView didSelectRowAtIndexPath 没有被调用
【发布时间】:2015-05-17 21:10:25
【问题描述】:

IOS 开发新手,在处理表格上的单元格选择时遇到问题。每当我选择时,该方法都不会在下面被调用 - 知道为什么吗?

我的项目结构是: 视图控制器 -> 视图 -> 表视图

下面的代码演示了方法调用。别人叫没问题!我知道触摸正在工作,因为下拉成功刷新并且单击单元格时它会突出显示。

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.
  }
}

【问题讨论】:

  • 您是否将自己设置为表视图委托?

标签: ios swift


【解决方案1】:

您必须将@IBOutlet 设置为ViewController 中的tableView,并将其设置为delegatedataSource,这样您才能看到数据并响应tableView 中的更改。

类似这样的:

override func viewDidLoad() {
    super.viewDidLoad()

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

并且也实现了UITableViewDataSource 协议。

或者您也可以在 Interface Builder 中将 ViewController 设置为委托和 dataSource(我认为这样做更容易)并避免在上面的代码中手动设置。由你决定。

希望对你有所帮助。

【讨论】:

  • 或者不要继承UIViewController,而是使用UITableViewController - 这样你就可以免费获得很多功能。例如,UITableView 已经为您设置好了,代表指向您的视图控制器。
  • 谢谢,效果很好! (我选择了将 View Controller 设置为委托出口的快速选项。
  • .delegate = self 为我彻底解决了这个问题。我很惊讶我以前没有这样做。看起来表格视图可以在不设置此委托值的情况下打包大量功能。
  • Google 同事们:你必须在你的类声明中传入UITableViewDelegate 才能让.delegate 工作!!例如,我的班级名为PickFavVC。这就是我在PickFavVC.swift 中拥有的:class PickFavVC: UIViewController, UITableViewDataSource, UITableViewDelegate {
【解决方案2】:

比较两个相同的代码示例时,我遇到了同样的问题,其中一个运行良好,另一个没有调用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(这是我的问题,因为 Storyboard 更改在 .swift 控制器类中不可见。

打开文档大纲和Control + Press 你的TableView 您将看到两个名为“delegate”和“dataSource”的网点 将它们一一拖到包含ViewController(右到黄色圆圈上)

就是这样!

【讨论】:

    【解决方案3】:

    你必须使用这个:首先看看你在扩展什么,然后使用 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
        }
    }
    

    【讨论】:

      【解决方案4】:

      SWIFT 3

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

      在swift 3中使用上面的委托方法

      【讨论】:

      • 也添加覆盖
      【解决方案5】:

      大家都提到要设置tableView的dataSource和delegate。 但是设置后也不能正常工作,有时可能会因为没有或禁用表格视图的选择而发生。

      启用它 进入storyboard -> 选择tableView -> 点击属性检查器 -> 进入选择器 -> 选择单选(或根据要求多选)

      请根据您的适用性查找随附的屏幕截图。

      【讨论】:

      • 是的,我首先禁用它(通过在 Storyboard 中将选择设置为无)以专注于使用自定义单元格实现列表,一旦我开始处理导航,我忘记了我已经禁用它,花了我一段时间找到此答案中突出显示的选项..
      • 是的。我也这样做了。这就是我发布这个答案的原因:P
      • Duuuuuude,你做了我的番茄钟。谢谢!
      • 就是这样。谢谢
      • 哇!就是这样,谢谢,你拯救了我的一天。
      【解决方案6】:
      • 几项可以帮助您的检查:-

        myTableView.allowsSelection = true

        myTableView.delegate = self

      • 确保您正确书写didSelectRowAt

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

      • 如果您在UITableViewCell 上使用UIButton,那么它会与单元格重叠,因此请检查Solution here

      【讨论】:

      • 在谷歌搜索 30 分钟左右后,你救了我!问题是我在创建表格视图时设置了myTableView.allowsSelection = true,谢谢!
      • @konekoya 很高兴我能帮上忙
      【解决方案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)
        

        【讨论】:

          【解决方案9】:

          如果你正在编辑你的 tableView:

          tableView.allowsSelectionDuringEditing = true
          

          【讨论】:

            【解决方案10】:

            另一个警告是点击手势识别器。使用点击手势识别器来处理具有表格视图的视图控制器中的不同逻辑是一个常见的用例,无论是退出触摸控制还是第一响应者。

              let tapGesture = UITapGestureRecognizer(target: self, action: #selector(viewTapped))
              view.addGestureRecognizer(tapGesture)
            

            例如这行代码处理在我的应用程序中关闭日期选择器并阻止我的 tableview 调用 didSelectRow 委托方法

            【讨论】:

              【解决方案11】:

              要检查的另一件事是您的类和方法的访问级别:

              我有一个标记为@objc public 的 Swift UIViewController 类,以使其对我的 Objective-c 代码可见。

              在这种情况下,您必须添加对该函数的公共访问权限,否则它将不会被调用。

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

              【讨论】:

                猜你喜欢
                • 2023-04-01
                • 1970-01-01
                • 2011-01-07
                • 2013-10-07
                • 1970-01-01
                • 2011-03-04
                相关资源
                最近更新 更多