【问题标题】:How to get textLabel of selected row in swift?如何快速获取所选行的textLabel?
【发布时间】:2014-11-27 07:42:05
【问题描述】:

所以我试图获取我选择的行的 textLabel 的值。我尝试打印它,但它不起作用。经过一番研究,我发现这段代码有效,但仅限于 Objective-C;

    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath    *)indexPath
    {
        NSLog(@"did select  and the text is %@",[tableView cellForRowAtIndexPath:indexPath].textLabel.text);]
    }

我找不到任何适用于 Swift 的解决方案。虽然打印 indexpath.row 是可能的,但这不是我需要的。

那我该怎么办?或者这段代码的“Swift 版本”是什么?

【问题讨论】:

    标签: uitableview swift ios8 tableview xcode6


    【解决方案1】:

    试试这个:

    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    
        let indexPath = tableView.indexPathForSelectedRow() //optional, to get from any UIButton for example
    
        let currentCell = tableView.cellForRowAtIndexPath(indexPath) as UITableViewCell
    
        print(currentCell.textLabel!.text)
    

    【讨论】:

    • 这对我有用!我唯一需要更改的是在indexPath 和UITableViewCell 之后添加!。非常感谢!
    • 从参数到 indexPath 和通过 tableView.indexPathForSelectedRow() 获取有什么不同?
    • 它是一样的。它应该只是向您展示一种获取当前选择的 indexPath 的方法。可能来自视图中的任何按钮。
    • Swift 4.1 let indexPath = tableView.indexPathForSelectedRow let cell = tableView.cellForRow(at: indexPath!)
    【解决方案2】:

    如果你的类继承自UITableViewController,那么这是 swift 版本:

    override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
        let cell = self.tableView.cellForRowAtIndexPath(indexPath)
        NSLog("did select and the text is \(cell?.textLabel?.text)")
    }
    

    请注意,cell 是可选的,因此必须解包 - textLabel 也是如此。如果 2 中的任何一个为 nil(不太可能发生,因为使用有效的索引路径调用该方法),如果您想确保打印有效值,那么您应该检查 cell 和 textLabel都不是零:

    override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
        let cell = self.tableView.cellForRowAtIndexPath(indexPath)
        let text = cell?.textLabel?.text
        if let text = text {
            NSLog("did select and the text is \(text)")
        }
    }
    

    【讨论】:

    • 嗨,我没有使用 TableViewController,只是 ViewController 中的 tableview。这对我来说很好,直到这一点。当我将你的代码粘贴到 ViewController 类中时,它会收到一个错误,上面写着method does not override any method from its superclass。这可以通过删除override-部分来解决。当我再次尝试运行代码时,它显示(UITableView, numberOfRowsInSection: Int) -> int' does not have a member named 'cellForRowAtIndexPath'。我该怎么做才能解决这个问题??
    • 你可能必须让视图控制器实现UITableViewDelegate协议,并将表格视图的delegate属性设置为self-viewDidLoad是个好地方
    【解决方案3】:

    斯威夫特 4

    获取选中行的标签:

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let cell = tableView.cellForRow(at: indexPath) as! TableViewCell
        print(cell.textLabel?.text)
    }
    

    获取取消选择行的标签:

    func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
        let cell = tableView.cellForRow(at: indexPath) as! TableViewCell
        print(cell.textLabel?.text)
    }
    

    【讨论】:

      【解决方案4】:

      如果要根据匹配的NSIndexPath 打印UITableViewCell 的文本,则必须使用UITableViewDelegate 的tableView:didSelectRowAtIndexPath: 方法并通过UITableView 获取所选UITableViewCell 的引用的cellForRowAtIndexPath: 方法。

      例如:

      import UIKit
      
      class TableViewController: UITableViewController {
      
          override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
              return 4
          }
      
          override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
              let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
      
              switch indexPath.row {
              case 0: cell.textLabel?.text = "Bike"
              case 1: cell.textLabel?.text = "Car"
              case 2: cell.textLabel?.text = "Ball"
              default: cell.textLabel?.text = "Boat"
              }
      
              return cell
          }
      
          override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
              let selectedCell = tableView.cellForRowAtIndexPath(indexPath)
              print(selectedCell?.textLabel?.text)
              // this will print Optional("Bike") if indexPath.row == 0
          }
      
      }
      

      但是,出于多种原因,我不鼓励您使用之前的代码。你的UITableViewCell 应该只负责显示模型给出的一些内容。 在大多数情况下,您需要根据NSIndexPath 打印模型的内容(可能是String 的Array)。通过这样做,您将分离每个元素的职责。

      因此,这是我的建议:

      import UIKit
      
      class TableViewController: UITableViewController {
      
          let toysArray = ["Bike", "Car", "Ball", "Boat"]
      
          override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
              return toysArray.count
          }
      
          override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
              let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
              cell.textLabel?.text = toysArray[indexPath.row]
              return cell
          }
      
          override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
              let toy = toysArray[indexPath.row]
              print(toy)
              // this will print "Bike" if indexPath.row == 0
          }
      
      }
      

      如您所见,使用此代码,您不必处理选项,甚至不需要在tableView:didSelectRowAtIndexPath: 中获取匹配的UITableViewCell 的引用来打印所需的文本。

      【讨论】:

        【解决方案5】:

        在 swift 4 中: 通过覆盖方法

        override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
                let storyboard = UIStoryboard(name : "Main", bundle: nil)
                let next vc = storyboard.instantiateViewController(withIdentifier: "nextvcIdentifier") as! NextViewController
        
               self.navigationController?.pushViewController(prayerVC, animated: true)
        }
        

        【讨论】:

          【解决方案6】:

          在我的情况下,我做了一些小的更改,当我在 tabelview 中搜索值时选择 (didSelectRowAtIndexPath) 单元格它返回单元格的索引,所以我在将一个 viewControler 移动到另一个时遇到问题。通过使用这个方法我发现重定向到新 viewControler 的解决方案

          let indexPath = tableView.indexPathForSelectedRow!
          let currentCellValue = tableView.cellForRow(at: indexPath!)! as UITableViewCell
          let textLabelText = currentCellValue.textLabel!.text
          print(textLabelText) 
          

          【讨论】:

            【解决方案7】:

            维护一个在cellforindexPath方法本身中存储数据的数组:-

            [arryname objectAtIndex:indexPath.row];
            

            在didselectaAtIndexPath 方法中也使用相同的代码.. 祝你好运:)

            【讨论】:

              【解决方案8】:

              这将起作用:

              let item = tableView.cellForRowAtIndexPath(indexPath)!.textLabel!.text!
              

              【讨论】:

              • 虽然这段代码 sn-p 可以解决问题,但including an explanation 确实有助于提高帖子的质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因。
              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2014-07-24
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多