如何从@IBAction中调用表视图函数

时间:2014-09-03 14:16:21

标签: uitableview swift

来自cellForRowAtIndexPath

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){

我需要在父表中调用一个函数,该函数将我传递的参数之一作为参数(ex param1)。

我该如何做到这一点?


在@rob给出的答案之后编辑:

最终有效的是

一个。将对父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 个答案:

答案 0 :(得分: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. 让您cellForRowAtIndexPath致电loadItem

    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中配置的层次结构。

    或者,您可以在@IBAction课程中实施PeopleTableViewCell,在这种情况下,您不能使用此sender.superview?.superview语法,而只能引用{{} 1}}获取self属性。它取决于你。