更新tableView swift中的头

我试图更新label.text我创build一个部分的标题,当我添加一个新的行而不重新加载整个部分。

目前我find了一个解决scheme,但是它需要大量的if语句。 我发现一个段的标题实际上也是一行,行的数量取决于iPhone的CPU架构,如果是32行号是2147483647,如果是64位,行号是9223372036854775807。

为iPhone 5我做

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

其中2147483647是标题的行号,….很酷,对不对?

现在我知道这不是一个好办法,我必须执行电话版本的检查。 有没有另外一种方法来做到这一点,或者我做的方式是好的?

制作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; } 

现在,你要改变UILabel的文本为前。 我点击button更改标签的文字

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

它会将lbl_header的文本更改为Hello …

您可以devise自己的标题,就像在表格视图中devise自定义单元格一样。 或者你可以像这样添加一个图像:

 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 } 

然后,您可以简单地将您的部分标题UILabel添加为另一个子视图。

Swift 3更新

 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; } 

现在可以通过访问其他地方的lvl_header.text来改变它。