我是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/