【问题标题】:Set margin on top of a tableview in IOS在IOS中的tableview顶部设置边距
【发布时间】:2017-10-29 02:42:05
【问题描述】:

我是使用 swift 进行 IOS 开发的新手,但遇到了问题。我需要创建一个表格视图,它看起来几乎是我想要的方式,除了表格第一部分顶部的空间。它没有名字,但我想减少顶部和第一项之间的空间。我能做的是根据下面的代码和图片:

override func numberOfSections(in tableView: UITableView) -> Int {
    return 2
}

override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    switch (section) {
        case 0:
            return ""
        default:
            return self.nameSection2
    }
}

override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let headerView = UIView()
    headerView.backgroundColor = UIColor.white
    let headerLabel = UILabel(frame: CGRect(x: 15, y: 8, width:
        tableView.bounds.size.width, height: tableView.bounds.size.height))
    headerLabel.font = UIFont(name: "Verdana", size: 16)
    headerLabel.textColor = UIColor.lightGray
    headerLabel.text = self.tableView(self.tableView, titleForHeaderInSection: section)
    headerLabel.sizeToFit()
    headerView.addSubview(headerLabel)
    return headerView
}

【问题讨论】:

    标签: ios swift tableview


    【解决方案1】:

    您看到的“边距”是因为两个部分标题的高度相同。第二个看起来不那么空,因为它实际上有一个标题。

    您可以修改标题的高度以减少空间:

    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        switch section {
            case 0: 
                return 0
            case 1: 
                return 44 //Required height value here
            default: 
                return defaultValue //Any default value
        }
    }
    

    【讨论】:

    • 非常感谢。我在这里得到它:D。
    【解决方案2】:

    您需要实现 heightForHeaderInSection 以便折叠该标题。见下文:

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 0 {
            return 1.0
        } else {
            return 32.0
        }
    }
    

    您可以根据需要为 else 条件设置适当的值,但这会给您提供思路。

    更新 #1:我在搜索中发现此链接也可能有所帮助:http://stackoverflow.com/a/23955420/3965

    建议使用 GLFloat 的最小值:

    if section == 0 {
         return CGFloat.leastNormalMagnitude
    }
    
    return tableView.sectionHeaderHeight
    

    【讨论】:

      【解决方案3】:

      实现 heightForHeaderInSection 并返回您想要的第一部分的高度。

      此外,您通常不会实现 titleForHeaderInSection 和 viewForHeaderInSection。只需将您的 switch 语句放在 viewForHeaderInSection 中即可为您的标签设置文本。

      而且你不需要将你的 UILabel 放入 headerView,只需返回标签。或者代替 UIView,使用 UITableViewHeaderFooterView。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多