【发布时间】:2009-12-05 05:31:08
【问题描述】:
我想为表格视图的每个单元格设置不同的图像。我不知道该怎么做——请帮帮我。
【问题讨论】:
标签: iphone objective-c uitableview uiimage
我想为表格视图的每个单元格设置不同的图像。我不知道该怎么做——请帮帮我。
【问题讨论】:
标签: iphone objective-c uitableview uiimage
创建一个属性来存储不同图像名称的数组。
在您的标头 (.h) 文件中:
@interface MyViewController : UITableViewController {
NSArray *cellIconNames;
// Other instance variables...
}
@property (nonatomic, retain) NSArray *cellIconNames;
// Other properties & method declarations...
@end
在您的实施 (.m) 文件中:
@implementation MyViewController
@synthesize cellIconNames;
// Other implementation code...
@end
在您的viewDidLoad 方法中,将cellIconNames 属性设置为包含不同图像名称的数组(按照它们想要出现的顺序):
[self setCellIconNames:[NSArray arrayWithObjects:@"Lake.png", @"Tree.png", @"Water.png", @"Sky.png", @"Cat.png", nil]];
在你的tableView:cellForRowAtIndexPath:表格视图数据源方法中,获取单元格所在行对应的图片名称:
NSString *cellIconName = [[self cellIconNames] objectAtIndex:[indexPath row]];
然后创建一个UIImage对象(使用cellIconName指定图像)并将单元格的imageView设置为这个UIImage对象:
UIImage *cellIcon = [UIImage imageNamed:cellIconName];
[[cell imageView] setImage:cellIcon];
在第 3 步之后,您的 tableView:cellForRowAtIndexPath: 方法将如下所示:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
/* Initialise the cell */
static NSString *CellIdentifier = @"MyTableViewCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
/* Configure the cell */
NSString *cellIconName = [[self cellIconNames] objectAtIndex:[indexPath row]];
UIImage *cellIcon = [UIImage imageNamed:cellIconName];
[[cell imageView] setImage:cellIcon];
// Other cell configuration code...
return cell;
}
【讨论】:
listIcon 应该是 cellIcon(我现在已经更正了代码)。 cellIconNames 是一个NSArray,所以我们把它当作一个数组来使用...
setCellIconNames,见developer.apple.com/iphone/library/documentation/cocoa/…。基本上,setCellIconNames 是一个改变cellIconNames 实例变量值的方法(它是自动生成的,因为我们已经声明了cellIconNames 属性)。这种类型的方法称为 mutator/setter。
您可以创建一个包含 UIImageView 的自定义单元格,但最简单的方法是在您的 -cellForRowAtIndexPath 表视图委托中设置默认 UITableViewCell 的内置图像视图。像这样的:
UITableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithFrame:CGRectZero];
//... other cell initializations here
}
[[cell imageView] setImage:image];
其中 image 是您通过从 URL 或本地应用程序包加载而创建的 UIImage。
【讨论】: