2015-07-13 117 views
0

我可以成功地使用DidSelectRowAtIndexPath将数据(authorID)传递给视图。 现在我尝试用Button IBACTION执行相同的segue,但是我找不到执行它的方法。我找不到在INACTION中使用NSIndexPath的方法。Swift - IBACTION如何执行segue

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { 
     performSegueWithIdentifier("ArticleSegue", sender: indexPath) 
     tableView.deselectRowAtIndexPath(indexPath, animated: true) 
} 

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { 
     if segue.identifier == "ArticleSegue"{ 
      let toView = segue.destinationViewController as! ArticleTableViewController 
      let indexPath = sender as! NSIndexPath 
      let authorid = articleList?[indexPath.row]["author_id"].int! 
      toView.authorid = authorid    
} 

@IBAction func favButtonDidTouch(sender: AnyObject) { 
//??? 
} 
+0

因此你的tableView中的每一行都有favButton?你使用自定义单元格吗? – florianpfisterer

+0

是的,我有一个自定义的单元格,每一行都有favButton –

回答

1

的一种方式,就是给你favButtons标签(如果你不使用UIView-标签为别的东西)。

这意味着当您在tableView:cellForRowAtIndexPath:配置你的,你只是说:

cell.favButton.tag = indexPath.row 

然后在IBAction为,创建一个NSIndexPath与标签,并调用SEGUE:

let indexPath = NSIndexPath(forRow: sender.tag, inSection: 0) 
self.performSegueWithIdentifier("ManualSegue", sender: indexPath) 

确保在这种情况下发件人是UIView(这里是UIButton)。

+0

我如何在prepareForSegue中调用它? if检查中出现“let indexPath = sender as!NSIndexPath”错误。错误是“无法将'UIButton'类型(0x111798f68)的值转换为'NSIndexPath'(0x10f670680)” –

+0

,那么您可能会通过Storyboard中的favButton配置一个segue。如果您点击故事板中的segue,请检查favButton是否突出显示。如果是这样,通过点击“发送”视图控制器并控制拖动到您的segue的目标视图控制器,删除segue并创建一个新的手动搜索。 – florianpfisterer

+0

谢谢,这是固定的... –

1

如果已经定义了SEGUE为两个视图控制器之间的手动SEGUE,你只需调用

performSegueWithIdentifier("ManualSegue", sender: self) 

另一种可能性是定义从按钮本身SEGUE到目标视图控制器。在那种情况下,它会自动发生;您既不需要IBAction也不需要致电performSegueWithIdentifier

0

有一个方法,它

performSegueWithIdentifier("ArticleSegue", sender:self) 
+0

我不能这样做,因为每一行都有一个uniq ID我需要通过segue –

0

分配到UIButton的标签在你

override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { 
    // Setup cell etc.. 
    .... 
    cell.favButton.tag = indexPath.row 
    ... 
    return cell 
} 

然后在你的操作方法,注意方法从AnyObjectUIButton!变化所以你可以访问标签属性。你可以解决这个问题,因为你只需要在小区(在此indexPath.row您articleList)的行

@IBAction func favButtonDidTouch(sender: UIButton!) { 
    performSegueWithIdentifier("ArticleSegue", sender:NSIndexPath(forRow: sender.tag, inSection: 0)) 
} 
+0

如何在prepareForSegue中调用“indexPath”? –

+0

由于您在发布的错误中传递的'NSIndexPath'对象与您在'didSelectRowAtIndexPath'中的传递方式相同,因此您将其称为与之前相同,因此显示您传递了错误的'UIButton'。 – sbarow