gpt4 book ai didi

objective-c - iOS - 具有两个不同图像的 UITableViewCell 子类

转载 作者:行者123 更新时间:2023-11-29 04:38:06 24 4
gpt4 key购买 nike

我对 UITableViewCell 进行子类化,使其在最左侧显示一个图像,然后在中间显示一些文本,然后在最右侧显示一些文本。

根据条件,此 UITableViewCell 子类将仅具有两个图像。当我在 UITableViewCell 子类中使用图像时,我之前做了什么,我已将它们声明为

static UIImage *image = nil; 

然后在 +(void)initialize我已经给他们分配了方法。这样做只是为了拥有图像的类实例,而不是使用资源将这些图像分配给 UITableViewCell 的每个实例。

所以我现在的问题是,取决于我的 UIViewController 中调用 cellForRowAtIndexPath 的条件方法我应该显示带有 imageA 或 imageB 的 UITableViewCell。所以在伪代码中它看起来像这样

if (conditionA) { 
// Set image of cell to be imageA
} else {
// Set image of cell to be imageB
}

那么如何使用子类 UITableViewCell 实现此目的?我正在考虑一种方法是观察 UITableViewCell 中的属性,当该属性发生变化时,我会相应地设置单元格图像,但这对于应该很容易的事情来说似乎有点臃肿?

理想的方法是在 UITableViewCell 的 init 方法中设置它,但这样我就无法重用这些单元格了,对吗?

最佳答案

您不必担心为每个实例创建冗余图像。 UIImage 类已经具有内置缓存,只要您使用 imageNamed: 选择器创建新的图像实例,它就不会创建新的图像实例。

来自 UIImageimageNamed: 方法的文档,

This method looks in the system caches for an image object with the specified name and returns that object if it exists. If a matching image object is not already in the cache, this method loads the image data from the specified file, caches it, and then returns the resulting object.

如果这两个图像是预定义的并且不会改变,那么您可以简化子类单元格的接口(interface)。只允许该子类的用户告诉它应该使用哪种类型的图像。您可以为此使用enum

在 UITableViewCell 的子类 header 中,创建枚举。使用适合您的用例的任何名称。

typedef enum {
ImageTypeOne,
ImageTypeTwo
} ImageType;

@property (nonatomic) ImageType imageType;

在实现内部,将生成的 setter 重写为:

- (void)setImageType:(ImageType)newImageType {
imageType = newImageType;

if (imageType == ImageTypeOne) {
theImageView.image = [UIImage imageNamed:@"one"];
}
else if (imageType == ImageTypeOne) {
theImageView.image = [UIImage imageNamed:@"two"];
}
// this will resize the image view to fit the image.
[theImageView sizeToFit];
}

在您的 cellForRowAtIndexPath: 方法中,只需根据条件设置此属性即可。

if (conditionA) { 
myCustomCell.imageType = ImageTypeOne;
} else {
myCustomCell.imageType = ImageTypeTwo;
}

关于objective-c - iOS - 具有两个不同图像的 UITableViewCell 子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10790859/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com