gpt4 book ai didi

ios - UICollection 手动加载更多单元格 Swift

转载 作者:可可西里 更新时间:2023-11-01 02:05:11 26 4
gpt4 key购买 nike

我制作了一个仅包含 2 个单元格的 UICollection,其页脚包含一个按钮“显示更多”。当我们点击按钮“显示更多”时,它应该在 UICollection 中追加 2 个单元格。

screen

我的问题是,当我单击按钮时,UICollection 不会重新加载并附加 2 个新单元格。我检查了关于无限滚动的不同帖子,但我无法解决我的问题。这是我的代码:

我的按钮和他的功能

    lazy var showMoreButton: UIButton = {            let button = UIButton(type: .system)            button.setTitle("Show me more", for: .normal)            button.addTarget(self, action: #selector(handleShowMore), for: .touchUpInside)            return button        }()    func handleShowMore(){            homeDatasource?.incrementNumberOfUser()            HomeDatasourceController().collectionView?.reloadData()          }

My collection`

var numberOfUser: Int = 2

class HomeDatasource: Datasource, JSONDecodable {

override func footerClasses() -> [DatasourceCell.Type]? {
return [UserFooter.self]
}


override func cellClasses() -> [DatasourceCell.Type] {
return [UserCell.self, TweetCell.self] //UserCell -> section 0 and TweetCell -> section 1
}

override func item(_ indexPath: IndexPath) -> Any? {
if indexPath.section == 1 {
return tweets[indexPath.item]
}
return users[indexPath.item]
}

override func numberOfItems(_ section: Int) -> Int {
if section == 1 {
return tweets.count
}
return numberOfUser //users.count
}

override func numberOfSections() -> Int {
return 2
}

func incrementNumberOfUser() {

if numberOfUser <= users.count {
numberOfUser = numberOfUser + 2
}
}


}

`

最佳答案

这一行

HomeDatasourceController().collectionView?.reloadData()  

似乎是原因。因为您正在创建一个新的“HomeDatasourceController”,尽管在重新加载时它应该已经存在。因此,您应该重用已经存在的“HomeDatasourceController”实例。

你在某处创建了一个实例,例如

let datasourceController = HomeDatasourceController()

现在在

中重用该实例
func handleShowMore() {
homeDatasource?.incrementNumberOfUser()
datasourceController.collectionView?.reloadData()
}

关于ios - UICollection 手动加载更多单元格 Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43443261/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com