首页 > 解决方案 > TableView 页脚位置不正确

问题描述

我的第一次尝试将页脚放置在正确的位置,但是它太靠近前导边距,这使我添加了 1 个约束来解决问题。这样做会导致页脚高于页眉,这显然不是预期的行为。我想做的就是从我的第一次尝试中增加 10 分的领先优势。想法?

第一次尝试:

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

    if section == 0 {
    
        let label = UILabel()
        label.text = "Your birth month is not set"
        label.font = UIFont.preferredFont(forTextStyle: .footnote)
        label.textColor = UIColor.gray
                    
        return label
    }
    
    return UIView()
}

第二次尝试:

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

    if section == 0 {
    
        let label = UILabel()
        view.addSubview(label)
        
        label.translatesAutoresizingMaskIntoConstraints = false
        let constraints = label.leadingAnchor.constraint(equalTo: view.layoutMarginsGuide.leadingAnchor, constant: 10)
        NSLayoutConstraint.activate([constraints])
        
        label.text = "Your birth month is not set"
        label.font = UIFont.preferredFont(forTextStyle: .footnote)
        label.textColor = UIColor.gray
                    
        return label
    }
    
    return UIView()
}

标签: iosswiftuitableviewfooter

解决方案


尝试放置此代码。根据您的要求进行框架更换。

func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
    let headerView = UIView(CGRect(x: 0, y: 0, width: tableView.frame.width, height: 50))
    let lblDate = UILabel(frame: CGRect(x: 10, y: 0, width: headerView.frame.width - 10, height: 50))
    headerView.addSubview(lblDate)
    lblDate.text = "text"
    return headerView
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
    return 50
}

推荐阅读