本文介绍了如何在iOS中以编程方式在UITableViewCells中添加图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要以编程方式在UITableViewCells
中添加不同的图像.我怎样才能做到这一点.我正在尝试一些代码.但是图像未显示在UITableViewCells
中.这是我的下面的代码.
I need to add different images in UITableViewCells
programmatically. How can I do that. I am trying some code. But the images are not displayed in UITableViewCells
.This is my code below.
-(void)viewDidLoad
{
arrImages=[[NSMutableArray alloc]initWithObjects:@"image.png",@"image2.png",@"image3.png",@"image4.png",@"image5.png",@"image6.png",@"image7.png",@"image8.png" nil];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *identifier=@"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"identifier"];
}
imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 48, 48)];
cell.imageView.image = [UIImage imageNamed:[arrImages objectAtIndex:indexPath.row]];
return cell;
}
推荐答案
在.h文件中创建NSArray的属性
Create a property of NSArray in your .h file
@property NSArray *imgArray;
在您的.m文件中合成
@synthesize imgArray;
将其写在您的viewDidLoad
write this in your viewDidLoad
- (void)viewDidLoad
{
[super viewDidLoad];
// Initialize images...
imgArray = [NSArray arrayWithObjects:@"yourFirstImageName.png", @"yourSecondImageName.png", @"yourThirdImageName.png",....., @"yourSeventhImageName.png", nil];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = @"SimpleTableItem";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 48, 48)]; // your cell's height should be greater than 48 for this.
imgView.tag = 1;
[cell.contentView addSubview:imgView];
imgView = nil;
UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
lbl.backgroundColor = [UIColor clearColor];
[lbl setTag:2];
[cell.contentView addSubview:lbl];
lblDisch = nil;
}
UIImageView *_imgView = (UIImageView *)[cell.contentView viewWithTag:1];
_imgView.image = [UIImage imageNamed:[imgArray objectAtIndex:indexPath.row]];
UILabel *_lbl = (UILabel *)[cell.contentView viewWithTag:2];
_lbl.text = [arrFont objectAtIndex:indexPath.row]; // arrFont is your array
return cell;
}
希望这会对您有所帮助.
Hope this will help you.
这篇关于如何在iOS中以编程方式在UITableViewCells中添加图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!