如何将UITableViewCell值正确地转换为字符串

时间:2015-11-22 22:52:32

标签: ios swift uitableview

所以我的代码看起来像这样:

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
  let selectedCell = tableView.cellForRowAtIndexPath(indexPath)! as UITableViewCell
  performSegueWithIdentifier("TVtoVCSegue", sender: selectedCell)        
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
  if segue.identifier == "TVtoVCSegue" {
  let otherViewController = segue.destinationViewController as! TTDetailCntr
  otherViewController.CurrentClass = String(sender!) as String
}

otherViewController.CurrentClass连接到另一个viewController的标签,其标签显示:

<UITableViewCell: 0x13f692230; frame = (0 132; 320 44); text = '10.d'; clipsToBounds = YES; autoresize = W; layer = <CALayer: 0x13f692600>>

它应该是&#34; 10.d&#34;在这种情况下。我怎样才能做到这一点?

我查了很多问题,如果你发现了重复,请告诉我或解释我做错了什么

提前致谢

2 个答案:

答案 0 :(得分:1)

您可以访问UITableViewCell&#34; cell&#34;的textLabel。像这样:

cell.textLabel?.text

因此,您希望在 prepareForSegue 功能

中进行以下更改
if let cell = sender as? UITableViewCell, text = cell.textLabel?.text {
   otherViewController.CurrentClass = text
}

答案 1 :(得分:0)

据推测,您可以在某个数组的表格视图中安装文本。您应该将所选单元格的索引记录到didSelectRowAtIndexPath中的实例变量中,然后使用该索引在prepareForSegue方法中为表中的该条目获取字符串。

这样的事情:

override func tableView(
  tableView: UITableView, 
  didSelectRowAtIndexPath indexPath: NSIndexPath)
{
  //You would need to create the instance var cellIndex
  self.cellIndex = indexPath.row
  let selectedCell = tableView.cellForRowAtIndexPath(indexPath)! as UITableViewCell
  performSegueWithIdentifier("TVtoVCSegue", sender: selectedCell)
}

override func prepareForSegue(segue: UIStoryboardSegue, 
  sender: AnyObject?) 
{
  if segue.identifier == "TVtoVCSegue" 
  {
    //This code assumes that myModel is an array of structs. 
    //Change this code to fit your data model 
    //(should be the same code you use to set the text in the cell.)
    let stringToPass = myModel[self.cellIndex].stringValue
    let otherViewController = segue.destinationViewController 
      as! TTDetailCntr
    otherViewController.CurrentClass = stringToPass
  }
}