1

在我的应用程序中,我有顶部导航栏和导航栏下方的表格视图。我有两行的 CollectionViewCell,它们以编程方式添加到 UITableViewHeader 中。当我将 TableView 滚动到顶部时,我希望标题在导航栏下方停止,并更新 TableView 标题高度,以便我只能显示一行。当 TableViewHeader 粘在导航栏上时,我只想做一个动画(比如 Shrinked),两个 collectionview 行应该通过降低 Header Height 变成一行。我怎样才能以编程方式做到这一点

下面是我显示 CustomHeaderView 的代码

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let headerView = UIView.init(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 183))
    let headerCell = tableView.dequeueReusableCell(withIdentifier: kLastPlayedidentifier) as! LastPlayedTVC
    headerCell.frame = headerView.frame
    headerCell.category = lastPlayedData
    headerView.addSubview(headerCell)
    return headerView
}

此外,我正在检查滚动位置以编程方式设置 tableview 标题高度,这对我来说并不成功。

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
    print(scrollView.contentOffset)
    if scrollView.contentOffset.y > 237 //This value is to check when the header reached the top position {
//Condition to check and animate the headerview height to make collectionview cell two rows into one rows.
    }

当标题在滚动时粘在顶部时,如何实现 TableViewHeader 高度更新。

任何帮助表示赞赏。

4

1 回答 1

0

您正在寻找的是“粘性标题”,并且您也想更改标题。

  • 粘性部分是自动内置的,我认为如果你只使用 UITableViewController(style: .plain),如果这对你不起作用,你可以谷歌粘性标题,并且有很多答案。

  • 关于改变高度或动画的部分。您做得对,只需执行以下操作:

    // 更新 viewForHeader 方法以考虑上面的 headerRows 变量

// 更新 viewForHeader 方法以考虑上面的 headerRows 变量

// default 2, you modify this in your scroll
var headerRows = 2

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { 
let height = headerRows == 2 ? 183 : 91
        let headerView = UIView.init(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: height))
        let headerCell = tableView.dequeueReusableCell(withIdentifier: kLastPlayedidentifier) as! LastPlayedTVC
        headerCell.frame = headerView.frame
        headerCell.category = lastPlayedData
        headerView.addSubview(headerCell)
        return headerView
    }

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        print(scrollView.contentOffset)
        if scrollView.contentOffset.y > 237 {
            updatedHeader.frame.size.height = 40
            self.tableviewObj.tableHeaderView = updatedHeader
            headerRows = 1 } else {
            headerRows = 2
        }
        self.tableView.reloadSectionHeaders()
    }

如果你想做一些动画,你会做的是在你的视图控制器的一个变量中存储对你的 headerView 的引用,并在你的 scrollViewDidScroll 中使用 UIView.animate{...}

希望这对人有所帮助。

于 2019-08-05T18:46:24.620 回答