2017-06-24 44 views
0

我想在iOS中使用swift将UIControls添加到静态TableViewHeaders中。目标是建立在默认外观的基础之上,因此UI将与未来的默认UI元素相匹配。使用Swift将按钮添加到静态TableView头

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

我的具体目标是:

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

由于这两个都与章节分组相关,所以标题是添加此功能的合理选择。

回答

1

有自定义静态标头TableViews两个主要选项:

willDisplayHeaderView提供了默认的视图,并允许它修改。简单的外观修改相当简单。添加按钮等交互功能有点复杂

viewForHeaderInSection返回标题的视图,该标题可以从nib加载或完全由代码创建。这样做的一个缺点是它不能访问标题的默认外观,并且Apple仅提供对一个默认(UIColor.groupTableViewBackground)的访问。

要在默认标题之上构建,需要使用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

找到(是回答我的问题,希望为浸出年后回来给的东西)

相关问题