我有两类 UICollectionViewCell - ComicStripViewCellA 和 ComicStripViewCellB。
代替
if (condition) {
ComicStripViewCellA *comicStripViewCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"comicStripCell" forIndexPath:indexPath];
comicStripViewCell.imageView.image = image;
// Common Code Section
comicStripViewCell.pageNumber.text = @"Something ...";
.
.
} else {
ComicStripViewCellB *comicStripViewCell = [collectionView dequeueReusableCellWithReuseIdentifer:@"comicStripCell" forIndexPath:indexPath];
comicStripViewCell.title.text = @"Something ...";
// Common Code Section
comicStripViewCell.pageNumber.text = @"Something ...";
.
.
}
我想优化代码,因为“公共代码部分”中的很多代码都是相同的。这就是我想要实现的目标:
Class myClass;
if (condition) {
myClass = NSClassFromString(@"ComicStripViewCellA");
} else {
myClass = NSClassFromString(@"ComicStripViewCellB");
}
myClass *comicStripViewCell = [collectionView dequeueReusableCellWithReuseIdentifer:@"comicStripCell" forIndexPath:indexPath];
comicStripViewCell.title.text = @"Something ...";
// Common Code Section
comicStripViewCell.pageNumber.text = @"Something ...";
.
.
我知道上面的代码不会编译。这只是为了说明我想要实现的目标。有什么方法可以动态地将 ComicStripViewCell 转换为一个类?
提前致谢!
谢谢大家的建议!我使用了@protocol,一切正常。