【问题标题】:How to add a label and UIButton to a tableViewSection header in Swift?如何在 Swift 中将标签和 UIButton 添加到 tableViewSection 标头?
【发布时间】:2018-03-12 22:56:46
【问题描述】:

我编写了以下代码,用于在节标题视图的中心添加文本标签。

代码的后半部分是添加一个UIButton,其宽度为100,并与节标题的右上角对齐。

结果是:只有添加的标签显示在中心。该按钮根本不显示在标题上!

能否请您指出我在实施中出了什么问题?谢谢。

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

    // code for adding centered title
    headerView.backgroundColor = UIColor.gray
    let headerLabel = UILabel(frame: CGRect(x: 0, y: 0, width:
        tableView.bounds.size.width, height: 28))
    headerLabel.textColor = UIColor.black
    headerLabel.text = titlesList[section]
    headerLabel.textAlignment = .center
    headerView.addSubview(headerLabel)

    // code for adding button to right corner of section header        
    let showHideButton: UIButton = UIButton(frame: CGRect(x:headerView.frame.size.width - 100, y:0, width:100, height:28)) 
    showHideButton.setTitle("Show Closed", for: .normal)
    showHideButton.backgroundColor = UIColor.blue
    showHideButton.addTarget(self, action: #selector(btnShowHideTapped), for: .touchUpInside)

    headerView.addSubview(showHideButton)

    return headerView
}

【问题讨论】:

    标签: ios swift uitableview uiview uibutton


    【解决方案1】:

    let showHideButton: UIButton = UIButton(frame: CGRect(x:headerView.frame.size.width - 100, y:0, width:100, height:28)

    按钮的 X 位置是 headerView 的大小减去 100。但是您的 headerView 没有框架 (let headerView = UIView()),这意味着它的宽度为 0。因此您的按钮位于 X -100。

    我想你打错字了,应该根据表格的宽度来定位它:

    let showHideButton: UIButton = UIButton(frame: CGRect(x:tableView.bounds.size.width - 100, y:0, width:100, height:28)

    【讨论】:

      【解决方案2】:

      你的问题是这一行:

      let headerView = UIView()
      

      您没有指定任何框架大小,因此下面的行将不是您的showHideButton 框架的可识别大小:

      let showHideButton: UIButton = UIButton(frame: CGRect(x:headerView.frame.size.width - 100, y:0, width:100, height:28))
      

      当你声明你的headerView时使用这一行:

      let headerView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 100)) 
      

      这将显示以下内容:

      【讨论】:

        猜你喜欢
        • 2020-08-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多