在UITableView静态单元格中更改标题

时间:2016-06-06 15:22:47

标签: ios swift uitableview

我有这个带静态单元格的UITableView:

image

我想更改标题字段并在单元格中水平居中。我怎么能用Swift?

提前致谢。

2 个答案:

答案 0 :(得分:2)

首先,当然你可以使用swift来做到这一点,现在这是你需要放在viewController中才能使这个工作的代码

您需要将viewController设置为UITableViewDelegate,然后实现此方法

func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return X; //X is the value of height of your header
}

func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let headerView = UIView(frame: CGRect(x: 0, y: 0, width: self.tableView.frame.size.width, height: X)) //X is the value of height of your header
    let label = UILabel(frame: headerView.frame)
    label.text = "TESTING"
    label.textAlignment = NSTextAlignment.Center
    headerView.addSubview(label)

    return headerView;
}

我希望这可以帮到你

答案 1 :(得分:0)

听起来你想要使用:

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

}

使用此功能,您可以对要查找的UI进行编码,创建标签并将框架设置为您需要的框架,并将文本设置为您想要的文本。如果检查或使用switch语句作为section,并且相应地设置文本,那么只需返回标签或视图,但是你决定实现你的解决方案。我在tableView页脚中做了类似的事情,我将发布代码并链接到文档以供参考:

func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
    let footerView = UIView.init(frame: CGRectMake(0, 0, tableView.frame.size.width, 50))
    //label
    let label : UILabel = UILabel.init(frame: CGRectMake(30, 0, 150, 50))
    label.text = "Calorie Total :"
    //label to hold calorie total for the section
    let totalLabel = UILabel.init(frame: CGRectMake(185, 0, 50, 50))
    var total = Int()

    //grab the total for the section
    switch section {
    case 0:
        total = calculateCalories(breakfastFoodArray)
        break
    case 1:
        total = calculateCalories(lunchFoodArray)
        break
    case 2:
        total = calculateCalories(dinnerFoodArray)
        break
    case 3:
        total = calculateCalories(snackFoodArray)
        break
    default:
        break
    }
    totalLabel.text = String(total)

    footerView.addSubview(label)
    footerView.addSubview(totalLabel)

    let footerExentsionView = UIView.init(frame: CGRectMake(0, 50, tableView.frame.size.width, 10))
    footerExentsionView.backgroundColor = UIColor.whiteColor()
    footerView.addSubview(footerExentsionView)
    return footerView
}