2015-07-13 105 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