这是在过去几年 iOS 开发中帮助过我的代码。
简单使用 CocoaPods
pod 'YZLibrary'
如果您正在使用 Swift,请将以下内容添加到您的 bridging header 中:
#import <YZLibrary/YZLibraryImportAll.h>
您可以在http://www.yichizhang.info/YZLibrary/doc/上查看文档
NSArray *fruitArray = @[@"Apple", @"Banana", @"Cherry"];
NSString *fruitForToday = [fruitArray yz_randomObject];
文件:UICollectionViewCell+YZLibrary UITableViewCell+YZLibrary
将 NIB 文件名和标识符设置为与单元格类的名称相同。
例如,您的自定义 TableView/CollectionView Cell 类是 'MyAwesomeCell'。将用户界面放在 'MyAwesomeCell.xib' 中;更改单元格标识符为 'MyAwesomeCell'。
然后您可以注册 nib 并非常懒地加载 cells
override func viewDidLoad() {
super.viewDidLoad()
...
// Register cell classes
MyAwesomeCell.yz_registerForCollectionView(self.collectionView)
...
}
override func collectionView(
collectionView: UICollectionView,
cellForItemAtIndexPath indexPath: NSIndexPath
) -> UICollectionViewCell {
let cell =
MyAwesomeCell.yz_dequeueFromCollectionView(
collectionView,
forIndexPath: indexPath
)
// Configure the cell
...
return cell
}
这可能是一种坏做法,但可以为您节省大量时间。
您可以为 custom NIB 文件名提供自己的标识符
let myAwesomeIdentifier = "AwesomeIdentifier"
let myAwesomeNibName = "AwesomeNib"
override func viewDidLoad() {
super.viewDidLoad()
...
// Register cell classes
MyAwesomeCell.yz_registerForCollectionView(
self.collectionView,
withNibFileName: myAwesomeNibName,
andReuseIdentifier: myAwesomeIdentifier
)
...
}
override func collectionView(
collectionView: UICollectionView,
cellForItemAtIndexPath indexPath: NSIndexPath
) -> UICollectionViewCell {
let cell =
MyAwesomeCell.yz_dequeueFromCollectionView(
collectionView,
forIndexPath: indexPath,
andReuseIdentifier: myAwesomeIdentifier
)
// Configure the cell
...
return cell
}