uitableview - iOS Swift How to change or update UILabel attribute in custom UITableViewCell -
i want update/change uilabel attribute (background color,background shape,etc...) dynamically when data web service.
i want dispaly label in difference type different lable text, update uilabel attribute according testdata got web server. : if testdata=[1,1,1,1] uilabel background color red , testdata=[2,2,2,2] uilabel background color blue.etc
i doing following:
in main.stroyboard:
i add tableview , tableviewcell (choice custom) associated uitableviewcell
named tvcell
, add uilabel component.
in tvcell
import uikit class tvcell: uitableviewcell { @iboutlet weak var testlabel: uilabel! var testdata:testdatainfo?{ didset{ updateui() } } private func updateui(){ if let mfildata=testdata{ setstauteslabel() } } private func setstauteslabel(){ self.testlabel=uilabel(frame: cgrect(x: 50, y: 50, width: 100, height: 35)) self.testlabel.text = "thistestlabel" self.testlabel.transform = cgaffinetransformmakerotation(0.2) self.superview?.addsubview(self.testlabel) } }
methode 1: in tableviewcontroller
func tableview(tableview: uitableview, cellforrowatindexpath indexpath: nsindexpath) -> uitableviewcell { let data = testdatainfo![indexpath.row] let cell = self.tv.dequeuereusablecellwithidentifier(storyboard.projectappliedcellindentifier,forindexpath: indexpath) if let filesdatacell = cell as? tvcell{ filesdatacell.testdata=data } return cell }
result 1
just 1 cell testlabel has been change , rest cell no display testlabel
methode 2: in tableviewcontroller
func tableview(tableview: uitableview, cellforrowatindexpath indexpath: nsindexpath) -> uitableviewcell { let data = testdatainfo![indexpath.row] let cell = self.tv.dequeuereusablecellwithidentifier(storyboard.projectappliedcellindentifier,forindexpath: indexpath) if let filesdatacell = cell as? tvcell{ filesdatacell.testdata=data // update testlable in there let testlable:uilabel=uilabel(frame: cgrect(x: 50, y: 50, width: 100, height: 35)) testlable.text = "thislabel" testlable.transform = cgaffinetransformmakerotation(0.2) cell.contentview.addsubview(testlable) } return cell }
result 2
can display testuilabel in cell. not update testlabel original add new uilabel
but why ? want update uilable in tvcell. can me?
don't create new instance of testlabel in tableviewcontroller. can directly access in tableviewcontroller filesdatacell.testlabel; since cells reused, adding new label keep on adding new labels without discarding previous labels.
Comments
Post a Comment