Sunday 15 April 2012

ios - Passing data from TableViewController to TableViewCell -



ios - Passing data from TableViewController to TableViewCell -

i created tableviewcontroller , i'm displaying info coming array. had create tableviewcellcontroller also, because need have button each row, has perform action.

so, part of tableviewcontroller:

struct person { var name:string var age:string var address:string } class mytableviewcontroller: uitableviewcontroller { var people = array<person>() override func viewdidload() { super.viewdidload() var x = person(name: "marco", age: "28", address: "street a") var y = person(name: "pippo", age: "90", address: "street b") people.append(x) people.append(y) } override func tableview(tableview: uitableview, cellforrowatindexpath indexpath: nsindexpath) -> mytableviewcell { allow cellid: string = "cell" var cell: mytableviewcell = tableview.dequeuereusablecellwithidentifier(cellid) mytableviewcell cell.textlabel!.text = people[indexpath.row].name homecoming cell } }

the table printed fine can see in next picture:

now, need access property address every time press button "address" can see in picture. tried next code, within class tableviewcontroller:

override func tableview(tableview: uitableview, cellforrowatindexpath indexpath: nsindexpath) -> mytableviewcell { allow cellid: string = "cell" var cell: mytableviewcell = tableview.dequeuereusablecellwithidentifier(cellid) mytableviewcell cell.textlabel!.text = people[indexpath.row].name cell.buttonplay?.tag = indexpath.row cell.buttonplay?.addtarget(cell, action: "playactionx:", forcontrolevents: uicontrolevents.touchupinside) homecoming cell }

and, tableviewcell correctly receive tag:

class tableviewcell: uitableviewcell { func playactionx(sender:uibutton!) { println(sender.tag) }

everything fine. problem is, cannot send strings within tag , don't know how access 'address' field tableviewcontroller.

what solution utilize that? ps. have tried create instance tableviewcontroller class:

func playactionx(sender:uibutton!) { println(sender.tag) allow instance:mytableviewcontroller = mytableviewcontroller() println(instance.getpeoplearray()) }

(getpeoplearray returning array people) strangely array receive it's empty , don't understand why.

thanks support

your getpeoplearray empty because creating new instance of mytableviewcontroller, not accessing existing one. don't go route. instead alter target/action buttons view controller, not cell. change:

cell.buttonplay?.addtarget(cell, action: "playactionx:", forcontrolevents: uicontrolevents.touchupinside)

to

cell.buttonplay?.addtarget(self, action: "playactionx:", forcontrolevents: uicontrolevents.touchupinside)

and move playactionx: function table view controller. there can utilize tag index people array.

ios uitableview swift parameter-passing

No comments:

Post a Comment