swift - CollectionView 标头 ReusableView
问题描述
我已经通过storyboard启用了collectionView中的header,然后我编码如下,但是Header没有出现。我想知道有人看到任何问题吗?
AskViewController.swift
override func viewDidLoad() {
super.viewDidLoad()
askCollectionView.register(AskCollectionViewHeader.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "askCollectionViewHeader")
askCollectionView.delegate = self
askCollectionView.dataSource = self
}
extension AskViewController : UICollectionViewDelegateFlowLayout, UICollectionViewDataSource
{
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let header = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "askCollectionViewHeader", for: indexPath) as! AskCollectionViewHeader
header.askHeaderTitle.text = "Hi"
return header
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
referenceSizeForHeaderInSection section: Int) -> CGSize{
return CGSize(width: view.frame.size.width, height: 200)
}
}
AskCollectionViewHeader.swift
import UIKit
class AskCollectionViewHeader : UICollectionReusableView {
@IBOutlet weak var askHeaderTitle: UILabel!
}
解决方案
您正在注册一个类,但没有任何实例化此视图的askHeaderTitle
.
使用集合视图标题,您有三个选项:
在故事板场景中定义可重用视图(通过将“Collection Reusable View”拖到您在 Interface Builder 中设置的集合视图上)。在这种情况下,您将在 IB 中指定类和重用标识符,并且您根本不会调用
register
,viewDidLoad
而是让情节提要来处理。在 NIB 中定义可重用视图。在这种情况下,您将在 IB 中注册 NIB,而不是在课程中。
以编程方式定义可重用视图。只有在这种情况下,您才会
register
在课堂上使用。但是话又说回来,该子类不会使用@IBOutlet
(因为您没有在 IB 中定义它),并且您将以编程方式创建子视图。
我认为选项 1 是最简单的,但显然只适用于使用情节提要和单元原型的情况。如果您计划从多个视图控制器中使用一些可重用的视图,则选项 2 很有用。如果您想手动完成所有操作,选项 3 是一种可能会采用的技术。
推荐阅读
- xaml - 绑定到 ElementName 取决于绑定顺序
- c# - UWP+Prism MVVM - 如何通过 XAML 设置视图模型属性的值?
- javascript - 使用 jQuery/JS 设置与具有特定内容的任何标题相邻的样式有序列表
- angular - 动态创建的对象发出的 Angular 捕捉事件
- c# - .NET Core 多个 IDbConnection 通过 AddTransient 实现
- javascript - 模态3主要问题
- excel - VBA - 单击按钮时删除 MultiUserEditing
- asp.net-web-api2 - Web Api 路由:找到多个与 URL 匹配的控制器类型
- java - Spring ConstraintValidator vs MultipartFile
- java - 通过java列出hadoop集群中的所有yarn应用