获取TableView中cell中的label的text出错!

    //通过唯一表示符搜索
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        //获取视图
        let viewController = self.storyboard?.instantiateViewControllerWithIdentifier("content") as! ViewController
        //获取当前点击的cell
        let cellIndex = tableView .cellForRowAtIndexPath(indexPath)
        //给标题赋值
        viewController.rowIndex = "\(cellIndex?.detailTextLabel?.text)"       
        //跳转压栈
        self.navigationController?.pushViewController(viewController, animated: true)
    }

获取到的结果是空的,nil。请问是我获取的方式不对还是思路不对呢?

阅读 4.4k
3 个回答

一般思路应该是这样的:你的 UITableView 需要展示的数据是放在一个 NSArray 类似的容器中,点击某个 Cell 时获取这个 Cell 对应的数据,是在 UITableView 点击 Cell 的回调方法中获取这个 Cell 的 IndexPath,再用这个 IndexPath 去 NSArray 里取得数据,而不是直接从 Cell 上拿数据。

你用的是UItableviewCell吗?

//通过唯一表示符搜索
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        //获取视图
        let viewController = self.storyboard?.instantiateViewControllerWithIdentifier("content") as! ViewController
        
        //方法一
        //获取当前点击的cell
        let cellIndex = tableView .cellForRowAtIndexPath(indexPath)
        //获取cell中的label对象
        var textLabel : UILabel? {
            get{
                return cellIndex?.textLabel;
            }
        }
        //提取label中的text属性内容,并将其传入视图属性
        viewController.rowLabelText = (textLabel?.text)!
        
        //方法二(精简方法一)
        viewController.rowLabelText = (cellIndex?.textLabel?.text)!
        
        //跳转压栈
        self.navigationController?.pushViewController(viewController, animated: true)
    }

可以通过上诉两个方法获取!

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题