【问题标题】:ios 8 swift - how to add footer for tableview using separate datasourceios 8 swift - 如何使用单独的数据源为 tableview 添加页脚
【发布时间】:2015-07-12 01:50:31
【问题描述】:

我试图解决这个问题 2 天。 我只想在我的表格视图中添加一个页脚(自定义单元格)。 我有一个视图,上面有一些东西(标签、按钮),我添加了一个表格视图。 为了有一个干净的控制器,对于数据源,我使用了一个单独的文件:

class MyDataSource: NSObject, UITableViewDataSource, UITableViewDelegate {
 ...   
}

在我的控制器中,我有:

class MyViewController: UIViewController {

    @IBOutlet weak var myButton: UIButton!
    var myDatasource: MyDataSource!
    @IBOutlet weak var myTableView: UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()
        myDatasource = MyDataSource(....)
        myTableView.dataSource = myDatasource
        // Do any additional setup after loading the view.
    }

所以,我在MyDataSource 中添加了:

 func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let footerView = UIView(frame: CGRectMake(0, 0, tableView.frame.size.width, 40))
        footerView.backgroundColor = UIColor.blackColor()
        return footerView
    }

     func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 40.0
    }

并且这段代码没有被调用。 我查看了文档,发现最后这两种方法是 UITableViewController 的一部分,而不是 UITableViewDataSource 的一部分。

那么,我的问题是,如何实现呢?

谢谢。

C.C.

【问题讨论】:

  • 它是一个委托方法...您是否使用视图控制器设置了 tableview 委托
  • tableView(tableView: UITableView, viewForFooterInSection section: Int) 是 UITableViewDelegate 协议的一部分,您必须将 tableview 委托设置为 myDatasource。在您的代码中,您没有给出 myTableView.delegate = myDatasource
  • 是的,这太愚蠢了。我刚刚看到,我没有为我的 tableview 放置代理。现在可以了。

标签: ios uitableview swift tableview tableviewcell


【解决方案1】:

Swift 3(注意下划线):

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

override func tableView( _ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat 

【讨论】:

    【解决方案2】:

    如前所述,显示页眉和页脚需要实现UITableViewDelegate协议的相关方法。对于页脚,它是:

    tableView(tableView: UITableView, viewForFooterInSection section: Int)
    

    确保您的表格视图的委托设置正确。

    另外,请注意还有另一个方便的表格视图功能:将添加到整个表格视图下方的页脚,无论数据源或委托实现如何。只需分配一个tableFooterView。

    【讨论】:

      猜你喜欢
      • 2019-05-30
      • 1970-01-01
      • 2011-02-21
      • 2017-04-05
      • 2021-12-04
      • 2023-01-03
      • 2020-11-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多