ios - 如何将单元格标签的值从 tableView 传递到其他 View?

标签 ios iphone swift uitableview label

我是IOS编程的初学者,也是整个编程的初学者。

(我有 XCODE 6.4)

看了那么多教程,还是没找到我需要的资料。

我有一个为标签赋值的代码:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let identifier = "formuleTableViewCell"

    let cell = tableView.dequeueReusableCellWithIdentifier(identifier, forIndexPath: indexPath) as! formule



    let formuleCommand = formulesList[indexPath.row]

    // Configure the cell...

    var shortCut = formuleCommand.formuleText

    cell.formuleLabel.text = shortCut



    return cell
}

然后,我有一个代码,它必须获取标签的名称(我想是这样)

var valueToPass:String!

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

    // Get Cell Label
    let indexPath = tableView.indexPathForSelectedRow();
    let currentCell = tableView.cellForRowAtIndexPath(indexPath!) as UITableViewCell!;

    let identifier = "formuleTableViewCell"

    let cell = tableView.dequeueReusableCellWithIdentifier(identifier, forIndexPath: indexPath!) as! formule

    valueToPass = cell.formuleLabel.text
    performSegueWithIdentifier("detail", sender: self)


}

最后是代码,它将数据从标签传递到另一个 ViewController

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    if (segue.identifier == "detail") {

        // initialize new view controller and cast it as your view controller
       var viewController = segue.destinationViewController as! specialitiesViewController
        // your new view controller should have property that will store passed value
        viewController.passedValue = valueToPass



    }

}

它必须这样工作: 表格 View 获取单元格的数据(这里没有代码) 然后,调用 TablView 的方法必须获取单元格的标签。 最后,我单击单元格,然后移动到另一个 ViewController,我的单元格标签数据打印在另一个标签中。

但它不起作用,所以当我单击单元格时,我移动到 ViewController,Label 中的文本等于 nil(我看不到任何文本)。为什么会这样?帮我解决这个问题!

感谢您的所有建议!

最佳答案

您的问题是您正在使用函数dequeueReusableCellWithIdentifier 来获取单元格,并且此方法仅在单元格已标记为准备好重用时返回该单元格。

您需要使用 cellForRowAtIndexPath这与委托(delegate)方法不同,小心获取单元格,更改您的 didSelectRowAtIndexPath 如下所示:

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

   // get cell label
   let cell = tableView.cellForRowAtIndexPath(indexPath) as! formule

   self.valueToPass = cell.formuleLabel.text
   self.performSegueWithIdentifier("detail", sender: self)
}

希望对你有帮助

关于ios - 如何将单元格标签的值从 tableView 传递到其他 View?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31860932/

相关文章:

ios - 在 iOS11 中更改 UISearchBar 背景图片

ios - 我怎样才能创建如下图所示的plist?

ios - 处理 iPhone 5、6 和 6 Plus 的高度和宽度尺寸(磅)

Swift - 有没有办法检查是否未使用可变参数?

json - 反序列化 JSON swift 4.2

ios - 如何在解析网页内容时单击按钮

ios - 最小和最大缩放 Xcode Swift

javascript - 使用 Node.js 验证 iOS 收据

javascript - iOS jQuery 更改输入值失败, "addClass"调用失败

ios - 即使应用程序更新后,持久数据仍然导致应用程序崩溃