0

I'm trying to update the label.text I create in the header of a section when I add a new row without reloading the entire section.

Currently I found a solution but it requires a lot of if statements. I found out that the header of a section is actually a row as well, and the number of the row depends on the cpu architecture the iPhone has, if it's 32 the row number is 2147483647 if it's 64bit the row number is 9223372036854775807.

for iPhone 5 I do

self.tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow:2147483647, inSection:1)], withRowAnimation: .Fade)

where 2147483647 is the row number of the header, ....cool, right?

Now I know this is not a good way to do it and I have to implement checks for the phone version. Is there another way to do this or the way I do it is fine?

Victor --------
  • 512
  • 1
  • 11
  • 29

3 Answers3

1

Make object of UILabel

 var lbl_header = UILabel()


 func tableView(tableView: UITableView, viewForHeaderInSection  section: Int) -> UIView?
  {

    self.lbl_header.frame = CGRectMake(0, 0, 320, 15)
    self.lbl_header.text = "Test"
    self.lbl_header.backgroundColor = UIColor.redColor()
  return self.lbl_header;

  }

Now it you want to change UILabel's text For ex. i click on button change label's text

  @IBAction func update_lbl_click(sender: UIButton)
   {
     self.lbl_header.text = "Hello"
   }

It will change lbl_header's text to Hello...

Bhoomi Jagani
  • 2,413
  • 18
  • 24
0

You could design your own header, like you would design a custom cell in a table view. Or you could just add an image like so:

func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

    var myCustomView: UIImageView
    var myImage: UIImage = UIImage(named: "myImageResource")
    myCustomView.image = myImage

    let header: UITableViewHeaderFooterView = view as UITableViewHeaderFooterView
    header.addSubview(myCustomView)
    return header
}

Then you can simply add your section title UILabel as another subview.

Rahul Mayani
  • 3,761
  • 4
  • 25
  • 40
0

Swift 3 update

var lbl_header = UILabel()

func tableView(tableView: UITableView, viewForHeaderInSection  section: Int) -> UIView?
{
  self.lbl_header.frame = CGRect(x: 0, y: 0, width: 200, height: 21)
  self.lbl_header.text = "Test"
  self.lbl_header.backgroundColor = UIColor.green
  return self.lbl_header;
}

Now, it can be changed by accessing lbl_header.text from somewhere else.

Dorian Roy
  • 3,094
  • 2
  • 31
  • 51