如何在 Swift 中从 viewForHeaderInsection 输出一行的值?

问题描述 投票:0回答:1

我想获取posts中的indexPath.row值,将其放入view.post中,然后返回,以便这些值出现在标题中(这样我点击的帖子的内容就可以过来了,我发现第一篇文章的内容是通过view.post = posts.first设置过来的,但是由于没有像cellForRowAt这样的indexpath,所以我找不到它并留下了一个问题

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = tableView.dequeueReusableHeaderFooterView(withIdentifier: "DetailContentView") as! DetailContentView

        view.post = posts.first
        //view.post = posts[indexPath.row]
        
        return view
    }

如果您能回答我是否可以使用该部分来获取行的值,我将不胜感激。

ios swift uitableview
1个回答
0
投票

有一个

UITableViewDataSource
协议指定行数和节数。它们是 numberOfSectionsnumberOfRowsInSection

一般来说,每个部分只有一个页眉和一个页脚。正如您在这种情况下所说的,您希望每个

Row
都有自己的
Header
,这是不可能的。但您可以尝试另一种方法,将
numberOfRow
numberOfSection
交换。这意味着您将有多个部分,每个部分将有一个单元格。

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    1
}

func numberOfSections(in tableView: UITableView) -> Int {
    posts.count
}

现在,您可以将每个

Header
 出队 
Post

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let view = tableView.dequeueReusableHeaderFooterView(withIdentifier: "DetailContentView") as! DetailContentView
    view.post = posts[section]
    //TODO: 
    return view
}
© www.soinside.com 2019 - 2024. All rights reserved.