ios - 使用 Swift 将按钮添加到静态 TableView 标题

标签 ios swift uitableview

我正在尝试使用 swift 将 UIControl 添加到 iOS 中的静态 TableViewHeaders。目标是建立在默认外观之上,以便 UI 将与 future 的默认 UI 元素相匹配。

我找到了一个很好的例子 modifying the appearance of existing elements , 但没有添加新的。

我的具体目标是:

  1. “全选”功能可快速将一个部分中的所有行标记为“已选中”(可以是复选标记配件、UISwitch 等)
  2. “显示/隐藏”功能允许单个 View 按部分提供简单的“概览”,同时仍然提供对部分内部详细信息的访问。

由于这两者都与部分分组相关,因此标题是添加此功能的合理选择。

最佳答案

为 TableView 自定义静态 header 有两个主要选项:

willDisplayHeaderView 提供默认 View 并允许对其进行修改。简单的外观修改非常简单。添加按钮等交互功能有点复杂

viewForHeaderInSection 返回 header 的 View ,可以从 nib 加载或完全在代码中创建。这样做的一个缺点是它无法访问 header 的默认外观,而 Apple 仅提供对一种默认外观 (UIColor.groupTableViewBackground) 的访问。

要在默认 header 之上构建,需要使用 willDisplayHeaderView。

override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int)
{    
    let header = view as! UITableViewHeaderFooterView
    let headerLabelFont: UIFont = header.textLabel!.font

    // References for existing or new button
    var selectButton: UIButton? = nil

    // Check for existing button
    for i in 0..<view.subviews.count {
      if view.subviews[i] is UIButton {
          selectButton = view.subviews[i] as? UIButton
      }
    }

    // No button exist, create new one
    if selectButton == nil {
      selectButton = UIButton(type: .system)
      header.addSubview(selectButton!)
      toggleButton = UIButton(type: .system)
      header.addSubview(toggleButton!)
    }
    // Configure button
    selectButton?.frame = CGRect(x: view.frame.size.width - 85, y: view.frame.size.height - 28, width: 77, height: 26)
    selectButton?.tag = section
    selectButton?.setTitle("SELECT ALL", for: .normal)
    selectButton?.titleLabel?.font = UIFont(descriptor: headerLabelFont.fontDescriptor, size: 11)
    selectButton?.contentHorizontalAlignment = .right;
    selectButton?.setTitleColor(self.view.tintColor, for: .normal)
    selectButton?.addTarget(self, action: #selector(self.selectAllInSection), for: .touchUpInside)

}

func selectAllInSection() {
    ...

最大的挑战是解决静态标题单元格可以被 TableView 重复使用这一事实。因此,如果修改了一个按钮,例如通过添加一个按钮,那么当它被重新使用时,可以添加第二个按钮。这仅在 TableView 大到足以滚动出屏幕时才会出现问题,但应加以防范,因为结果很难追踪。

如果将多个按钮添加到标题,则需要某种机制来识别每个按钮。 UIButton.tag 是一个选项,但在此示例中,该字段用于标识要操作的部分。另一种选择是使用标记字符串来包含两条信息。

可以在 Github 上找到完整的工作演示

(是的,回答我自己的问题,想在浸出多年后回馈一些东西)

关于ios - 使用 Swift 将按钮添加到静态 TableView 标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44735440/

相关文章:

swift - 声音导致游戏在 swift sprite 套件游戏中滞后?

ios - 如何在 iOS 应用程序中使用 SiriKit 集成视觉代码?

iOS后台队列检索数据两次?

ios - 如何在 iOS 中从一个应用程序获取信息到另一个应用程序

iphone - 从另一个 View 中选择 TableView 的行

ios - 清除 UITableView 中的单元格以将其他 View 放在单元格上

ios - UITableViewCellaccessoryType什么时候统一的?

ios - IPA 设置创建失败

ios - 重新加载 map 注释时出现问题

ios - 如何动态填充屏幕宽度标签?