Swift:UITableView节标题样式

Swift:UITableView节标题样式,swift,uitableview,Swift,Uitableview,我有一个UITableView,它有几个标题,但字体大小比我想要的大得多: 我在系统首选项中看到,苹果使用大写部分标题,字体较小,底部对齐如下: 我知道我可以使用viewForHeaderInSection创建自己的布局,但我的问题是,有没有一个简单的选项可以调用这种标准操作系统风格,而无需重新设计轮子?结果很简单: 您只需选择“分组”样式。结果很简单: 您只需选择“分组”样式。对于较小的字体大小和底部对齐的系统首选项,如Apple使用大写部分标题,我们必须使用UITableView的委

我有一个UITableView,它有几个标题,但字体大小比我想要的大得多:

我在系统首选项中看到,苹果使用大写部分标题,字体较小,底部对齐如下:


我知道我可以使用viewForHeaderInSection创建自己的布局,但我的问题是,有没有一个简单的选项可以调用这种标准操作系统风格,而无需重新设计轮子?

结果很简单:


您只需选择“分组”样式。

结果很简单:


您只需选择“分组”样式。

对于较小的字体大小和底部对齐的系统首选项,如Apple使用大写部分标题,我们必须使用UITableView的委托方法

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

        let headerView = UIView()
        headerView.backgroundColor = UIColor.lightGray

        let sectionLabel = UILabel(frame: CGRect(x: 8, y: 28, width:
            tableView.bounds.size.width, height: tableView.bounds.size.height))
        sectionLabel.font = UIFont(name: "Helvetica", size: 12)
        sectionLabel.textColor = UIColor.black
        sectionLabel.text = "NETWORK SETTINGS"
        sectionLabel.sizeToFit()
        headerView.addSubview(sectionLabel)

        return headerView
    }

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 50
    }
可以使用此方法设置自定义字体系列和节标题的对齐方式

viewForHeaderInSection方法仅用于设置默认字体系列和节标题对齐方式


希望这会对您有所帮助。

对于较小的字体大小和底部对齐的系统首选项,如Apple使用大写部分标题,我们必须使用UITableView的委托方法

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

        let headerView = UIView()
        headerView.backgroundColor = UIColor.lightGray

        let sectionLabel = UILabel(frame: CGRect(x: 8, y: 28, width:
            tableView.bounds.size.width, height: tableView.bounds.size.height))
        sectionLabel.font = UIFont(name: "Helvetica", size: 12)
        sectionLabel.textColor = UIColor.black
        sectionLabel.text = "NETWORK SETTINGS"
        sectionLabel.sizeToFit()
        headerView.addSubview(sectionLabel)

        return headerView
    }

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 50
    }
可以使用此方法设置自定义字体系列和节标题的对齐方式

viewForHeaderInSection方法仅用于设置默认字体系列和节标题对齐方式


希望这会对您有所帮助。

效果很好,谢谢。但是如果我想让sectionLabel水平居中呢?请非常感谢。我试过了,但没有成功。我想帧CGRect需要更改。然后我尝试添加:sectionLabel.textAlignment=.center,但没有运气。效果很好,谢谢。但是如果我想让sectionLabel水平居中呢?请非常感谢。我试过了,但没有成功。我想帧CGRect需要更改。然后我尝试添加:sectionLabel.textAlignment=.center,但没有成功。