可重用视图
为什么?
这个扩展包解决了以下问题
- 通过以下方式强制您的团队遵守标准实践:
- 将Storyboard标识符与其类名相同
- 将UITableViewCell和UICollectionViewCell重用标识符与其类名相同
- 将UICollectionView副视图和UITableViewHeaderFooterView重用标识符与其类名相同
- 在取回单元格/头视图时,不需要强制解包或强制转换
- 在从Storyboard实例化时,不需要强制解包或强制转换UIViewControllers
如果您是SwiftLint的用户,您将非常欣赏警告数量的减少,并且不再需要类似以下代码片段:
guard let cell = tableView.dequeueReusableCell(withIdentifier: "...", for: indexPath) as? MyCustomCellType else {
fatalError("We didn't get the cell")
}
示例
要运行示例项目,首先从仓库中克隆,然后从示例目录运行pod install
方便从NIB中创建视图
需要您的视图符合NibLoadableView
。
let view = MyNibLoadableView.create()
从Storyboard中创建UIViewController
要求类与其Storyboard标识符(Storyboard Identifier)相同。
let myStoryboard: UIStoryboard = ...
let myCustomViewController = myStoryboard.instantiateViewControllerOfType(MyCustomViewController.self) as MyCustomViewController
从Storyboard中创建UITableViewCell
要求类与复用标识符(Reuse Identifier)相同。您必须首先注册您的单元格类型。
// Registration
tableView.register(MyCustomCellType.self)
// Dequeueing
let cell = tableView.dequeueReusableCell(for: indexPath) as MyCustomCellType
从Storyboard中创建UICollectionViewCell
要求类与复用标识符(Reuse Identifier)相同。您必须首先注册您的单元格类型。
// Registration
collectionView.register(MyCustomCellType.self)
// Dequeueing
let cell = collectionView.dequeueReusableCell(for: indexPath) as MyCustomCellType
从Storyboard中创建UITableViewHeaderFooterView
要求类与复用标识符(Reuse Identifier)相同。您必须首先注册您的单元格类型。
// Registration
tableView.register(MyCustomHeaderFooterView.self)
/// Dequeueing
let header = tableView.dequeueReusableHeaderFooterView(inSection: section) as MyCustomHeaderFooterView
从Storyboard中创建UICollectionView的补充视图
要求类与复用标识符相同。您必须首先注册您的视图类型。
// Registration
collectionView.register(MyCustomSupplementaryView.self, forSupplementaryViewElementOfKind: .sectionHeader) // or .sectionFooter
// Dequeueing
let view = collectionView.dequeueReusableSupplementaryView(ofKind: .sectionHeader, for: indexPath) as MyCustomSupplementaryView // also takes .sectionFooter
使用 nib 支持的视图的注册
nib 支持的视图必须实现 NibLoadableView
协议。该协议有一个预定义的扩展,因此您的视图不需要添加任何方法或属性。
class MyCoolCell: UITableViewCell, NibLoadableView {
...
}
安装
ReusableViews 通过 CocoaPods 提供。要安装它,只需将以下行添加到您的 Podfile
pod "ReusableViews"
作者
Hesham Salman, [email protected]
Twitter: @WhatsASoftware
许可协议
ReusableViews 在 MIT 许可协议下提供。更多信息请参阅 LICENSE 文件。