ios - 重新加载数据在 Swift 的 HeaderView 中不起作用

标签 ios swift uicollectionview reload uicollectionreusableview

我无法更新CollectionView 的标题 View 的数据。此 header View 是 UICollectionReusableView 的子类。

我尝试调用一种方法在不同的地方重新加载此数据,但它们都没有触发更新。要查看更新的数据,我必须关闭并再次打开应用程序。

Collection View :

    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {

        guard kind == UICollectionView.elementKindSectionHeader else {
            fatalError("Unexpected element kind.")
        }

        let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "ProfileHeaderView", for: indexPath) as! ProfileHeaderView

         header?.reloadData()
//        headerView.userNameLabel.text = defaults.string(forKey: "username")

        return headerView
    }

标题 View :

class ProfileHeaderView: UICollectionReusableView {

    @IBOutlet weak var userNameLabel: UILabel!

    func reloadData() {

        let defaults = UserDefaults.standard
        usernameTextLabel.text = defaults.string(forKey: "username")

    }

我还尝试在 ViewWillAppearViewDidAppear 上调用 reloadData()

最佳答案

您可以尝试获取 header ,例如:

func reloadHeaderData() {
    guard let header = collectionView.supplementaryView(forElementKind: UICollectionView.elementKindSectionHeader, at: YourIndexPath) as? ProfileHeaderView else { return }
    header.reloadData()
}

关于ios - 重新加载数据在 Swift 的 HeaderView 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57933594/

相关文章:

ios - Swift 中的 UICollectionView 部分边框

ios - prepareForSegue 清空我的 NSManagedObject 数组

ios - UICollectionView 单元格留下巨大间隙所有设置设置为 0

ios - 作为选项卡的 subview 添加的 UIImageView 允许选择其下的控件

ios - XCode IBAction 和 IBOutlets 错误

android - 如何查看android静态库的ABI?

ios - 速度 : iOS Using NSPredicate filterUsingPredicate vs. for 循环

swift - scrollToItem水平滚动collectionView崩溃

swift - 如何从 Swift 项目组中的文件创建数组

ios - 滚动时更改 Swift Collection View 数据