Reputation: 83
I want to update/change a UILabel attribute (background color,background shape,etc...) dynamically when I get data from a Web service.
I want to dispaly this Label in difference type by different Lable text, update UILabel attribute according the testdata which got from web server. like that : if get testdata=[1,1,1,1] the UIlabel background color is red , testdata=[2,2,2,2] UILabel background color is blue.etc
I am doing the following:
In Main.Stroyboard:
I add TableView and TableViewCell (choice custom) associated UITableViewCell
named TVcell
and add a 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 One Cell testLabel has been change and 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 all cell. but not update testLabel original just add new UILabel
but why ? I want to update all UILable in TVCell. Can anyone Help me?
Upvotes: 2
Views: 838
Reputation: 1069
Don't create new instance of testLabel in TableViewController. You can directly access it in TableViewController by filesDataCell.testLabel; Since cells are reused, adding new label will keep on adding new labels without discarding previous labels.
Upvotes: 1