首页 > 解决方案 > Swift 5 - UIButtons 在 tableView 页脚与原始分隔线并排

问题描述

我正在尝试在tableView 页脚中以编程方式并排添加两个按钮(在左下角)。

我遇到的问题是在定义 tableView 页脚时我必须手动绘制分隔线,因为分隔线消失了。

如何在丢失原始分隔线的情况下简单地在 tableView 页脚的左下方添加两个按钮?

var terms_button = UIButton()
var policy_button = UIButton()

func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        
        //terms button
        terms_button = UIButton(frame: CGRect(x: 70, y: 0, width: 100, height: 50))
        terms_button.setTitle("Terms", for: .normal)
        terms_button.setTitleColor(UIColor.black, for: .normal)
        terms_button.titleLabel?.font = UIFont.roboto(size: 12, weight: .medium)
        terms_button.titleLabel?.alpha = 0.38
        terms_button.addTarget(self,action: #selector(didTapTermsButton),for: .touchUpInside)
        
        //policy button
        policy_button = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 50))
        policy_button.setTitle("Privacy Policy", for: .normal)
        policy_button.setTitleColor(UIColor.black, for: .normal)
        policy_button.titleLabel?.font = UIFont.roboto(size: 12, weight: .medium)
        policy_button.titleLabel?.alpha = 0.38
        policy_button.addTarget(self,action: #selector(didTapPolicyButton),for: .touchUpInside)

        let result = UIView()

            // recreate insets from existing ones in the table view
            let insets = tableView.separatorInset
            let width = tableView.bounds.width - insets.left - insets.right
            let sepFrame = CGRect(x: insets.left, y: -0.5, width: width, height: 0.5)

            // create layer with separator, setting color
            let sep = CALayer()
            sep.frame = sepFrame
            sep.backgroundColor = tableView.separatorColor?.cgColor
            result.layer.addSublayer(sep)
            result.addSubview(policy_button)
            result.addSubview(terms_button)

            return result
    }

标签: iosswiftxcodeuibuttontableview

解决方案


当您从 中返回您自己的let result = UIView()视图实例时viewForFooterInSection,您将丢弃 iOS 提供的原始内置默认视图。

你可以尝试的是 -

  1. 删除viewForFooterInSection实现
  2. 尝试使用 iOS 提供的默认内置视图
  3. 尝试自定义默认视图的外观,如下所示
func tableView(_ tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) {

    guard let footerView = view as? UITableViewHeaderFooterView else { return }
    
    let contentView = footerView.contentView
    // Try adding your buttons to this `contentView` 
}

这是尝试继续使用带有可能自定义的内置视图的唯一方法。如果这在不同的 iOS 版本中不能可靠地工作,您将需要返回viewForFooterInSection自定义视图实现。


推荐阅读