可重用
使用 xib 设置自定义单元格的简单方法
内容
需求
- iOS 8.0+
- Xcode 8.0+
- Swift 3.0+
安装
CocoaPods
CocoaPods 是一款用于 Cocoa 项目的依赖管理器。您可以使用以下命令安装它
$ gem install cocoapods
需要 CocoaPods 1.1.0+ 版本来构建 Reusable 1.0.0+。
要使用 CocoaPods 将 Reusable 集成到您的 Xcode 项目中,请在您的 Podfile
中指定它
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
use_frameworks!
target '<Your Target Name>' do
pod 'RSReusable'
end
然后,运行以下命令
$ pod install
使用
请确保您单元格的类名和 xib 的文件名使用相同的名称
- MyCell.swift
class MyCell: UITableViewCell, Reusable {
- MyCell.xib
UITableViewCell
使用 xib 定制的表格单元格
- 使单元格实现 Reusable 协议
import Reusable
//...
class MyCell: UITableViewCell, Reusable {
- (可选)创建自定义 xib 单元格并将单元格的类设置为 MyCell
- 从队列中取出单元格
import Reusable
//...
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeue(forIndexPath: indexPath) as MyCell
//setup cell ...
return cell
}
使用 xib 定制的表格头(脚注)
- 使头(脚注)继承自 BaseTableSectionHeaderFooterView 类
import Reusable
//...
class MySectionHeaderView: BaseTableSectionHeaderFooterView {
- (可选)创建自定义 xib 视图,并将文件所有者设置为您的类名 - MySectionHeaderView
- 从队列中取出头(脚注)视图
import Reusable
//...
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let header = tableView.dequeueHeaderFooterView() as MySectionHeaderView
//setup header ...
return header
}
UICollectionViewCell
使用 xib 定制的集合单元格
- 使单元格实现 Reusable 协议
import Reusable
//...
class MyCollectionCell: UICollectionViewCell, Reusable {
- (可选)创建自定义的xib单元格并将单元格的类设置为MyCollectionCell
- 从队列中取出单元格
import Reusable
//...
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueCell(for: indexPath) as MyCollectionCell
//setup cell ...
return cell
}
使用xib自定义收藏夹标题
- 创建标题(页脚)以实现可重用协议
import Reusable
//...
class CollectionHeaderView: UICollectionReusableView, Reusable {
- (可选)创建自定义xib视图(UICollectionReusableView)并将其类设置为CollectionHeaderView
- 出列视图
import Reusable
//...
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueCell(for: indexPath) as CollectionHeaderView
//setup header ...
return header
}
作者
Roman Sorochak - iOS开发者。您可以通过以下电子邮件联系我:[email protected]
许可证
可重用是根据MIT许可证发布的。有关详细信息,请参阅LICENSE。