I want to set a different image for each cell of my table view. I don't know how to do this -- please help me.
Create a property to store an array of different image names.
In your header ( .h
) file:
@interface MyViewController : UITableViewController { NSArray *cellIconNames; // Other instance variables... } @property (nonatomic, retain) NSArray *cellIconNames; // Other properties & method declarations... @end
In your implementation ( .m
) file:
@implementation MyViewController @synthesize cellIconNames; // Other implementation code... @end
In your viewDidLoad
method, set the cellIconNames
property to an array containing the different image names (in the order they want to appear):
[self setCellIconNames:[NSArray arrayWithObjects:@"Lake.png", @"Tree.png", @"Water.png", @"Sky.png", @"Cat.png", nil]];
In your tableView:cellForRowAtIndexPath:
table view data source method, get the image name that corresponds with the cell's row:
NSString *cellIconName = [[self cellIconNames] objectAtIndex:[indexPath row]];
Then create a UIImage
object (using cellIconName
to specify the image) and set the cell's imageView
to this UIImage
object:
UIImage *cellIcon = [UIImage imageNamed:cellIconName]; [[cell imageView] setImage:cellIcon];
After step 3, your tableView:cellForRowAtIndexPath:
method would look something like this:
- (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;
}
You can create a custom cell with a UIImageView in it, but the simplest way is to set the built in image view of the default UITableViewCell in your -cellForRowAtIndexPath table view delegate. Something like this:
UITableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithFrame:CGRectZero];
//... other cell initializations here
}
[[cell imageView] setImage:image];
Where image is a UIImage that you created by loading from a URL or from the local application bundle.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.