2014-09-03 41 views
1

內從cellForRowAtIndexPath內:如何調用表視圖功能從@IBAction

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

我創建一個UITableViewCell子類,PeopleTableViewCell

let cell:PeopleTableViewCell = self.tv_main.dequeueReusableCellWithIdentifier("row_cell") as PeopleTableViewCell 

,然後我通過一些參數

cell.loadItem(param1 as NSString, p2: param2) 

現在,在每一行中我都有一個按鈕,當我點擊它時

@IBAction func button_clicked(param1: NSString){ 

我需要調用在帶一個參數我傳遞的參數(如參數1)的一個父表的功能。

我該如何做到這一點?


編輯後,答案是@rob了:

什麼終於摸索是

A.傳遞給家長的UIViewController一個參考cell.loadItem

func cell.loadItem(param1 as NSString, controller: self) 

並將控制器變量分配給一個局部變量,比如pvcontroller

func loadItem(param1: String, controller: PeopleViewController) { 
     self.pvcontroller = controller 
} 

B.從PeopleTableViewCell類中,從按鈕的點擊函數中,我通過pvcontroller變量調用父的UIViewController的功能

@IBAction func person_image_click(sender: UIButton) { 
     self.pvcontroller?.person_clicked(self.param1) 
    } 
+1

順便說一句,確保'pvcontroller'是'weak',否則你可能會得到一個強大的參考週期。 – Rob 2014-09-06 11:06:32

回答

1

,你可以:

  1. 有一個PeopleTableViewCell屬於loadItem更新:

    class PeopleTableViewCell : UITableViewCell { 
    
        var param1: NSString? 
    
        func loadItem(param1: NSString, param2: NSString) { 
         self.param1 = param1 
    
         // do your other stuff here 
        } 
    
        // the rest of your implementation here 
    } 
    
  2. 有你的電話cellForRowAtIndexPathloadItem

    override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! { 
        let cell = tableView.dequeueReusableCellWithIdentifier("row_cell", forIndexPath: indexPath) as PeopleTableViewCell 
    
        let param1 = ... 
        let param2 = ... 
    
        cell.loadItem(param1, param2: param2) 
    
        return cell 
    } 
    
  3. 然後你@IBAction可能決定PeopleTableViewCell實例,並訪問其屬性。請注意,@IBAction參數sender像往常一樣引用按鈕。因此,如果這個@IBAction表視圖控制器被實施,那麼你就必須向上導航視圖層次結構才能到單元格,然後訪問從那裏屬性:

    @IBAction func buttonClicked(sender: UIButton) { 
        let cell = sender.superview?.superview as PeopleTableViewCell 
    
        let param1 = cell.param1 
    
        // do something with param1 now 
    } 
    

    在這個例子中,我在單元格的內容視圖上有按鈕,所以我要升級superview的兩個級別(一個獲取內容視圖,一個獲取單元格)。只要確保你在這裏做的任何事情都反映了你在IB中配置的層次結構。

    或者,你可以從PeopleTableViewCell類,在這種情況下,你不必使用這種sender.superview?.superview語法中實現你@IBAction,而是可以只是參考self獲取對param1財產。隨你便。