利用UITableView实现对图片的展示
前一段时间在[url=?u=3584]CocoaChina[/url]上看到过关于如何在Iphone中显示图片,今天就试试,顺便复习了一下UITableView了。先上两张图片了。
其实也是比较简单的了,首先在NSArray中加入要显示的图片的名称,方便后面的读取,然后就是再创建一个空的view用来显示需要展示的图片,在就是要创建一个UINavigationController,下面来看看具体怎么操作。
首先创建一个viewBased的空项目。添加一个新的xib文件和一个新类。名字自己取,然后关联你刚才的类和xib文件,实现controller控制model。
在创建的新类中定义一个UIImageView,用来显示展示的图片。还需要定义一个方法用来接收传过来的图片的名称。这样新的类基本上就创建好了。
打
开MainWindow.xib文件,向里面拖入一个NavigationController,在项目的delegate里面声明一个
UINavigationController,并且在window中加入该view。
[windowaddSubview:NavigationController.view],然后就是修改ViewController类了。引入你创
建的新类,声明一个用来保存图片名称的NSArray对象,和一个UITableView对象。在viewDidLoad中填充NSArray对象,初始
化UITableView,设置Delegates和DataSource。
-(void)viewDidLoad
{
array = [[NSArrayalloc]initWithObjects:@"p1.png",@"p2.png",@"p3.png",@"p4.png",@"p5.png",nil];
self.title = @"Pictures";
table = [[UITableView alloc]initWithFrame:CGRectMake(0,0,320,420)];
[table setDelegate:self];
[table setDataSource:self];
[self.view addSubview:table];
[table release];
[super viewDidLoad];
[table setSeparatorColor:[UIColorgreenColor]];//修改tableviewcell的线的颜色
}
下面就是用UITableView的3部曲了:
-(NSInteger)numberOfSectionsInTableView:(UITableView*)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableViewnumberOfRowsInSection:(NSInteger) section
{
return [array count];
}
-(UITableViewCell *)tableView:(UITableView *)tableViewcellForRowAtIndexPath:(NSIndexPath *)path
{
static NSString *s = @"s";
UITableViewCell *cell = [tableViewdequeueReusableCellWithIdentifier:s];
if(cell == nil)
{
cell = [[[UITableViewCellalloc]initWithFrame:CGRectZeroreuseIdentifier:s]autorelease];
UILabel *DataLabel = [[UILabelalloc] initWithFrame:CGRectMake(80, 0, 320, 44)];
[DataLabel setTag:100];
DataLabel.autoresizingMask =UIViewAutoresizingFlexibleWidth |UIViewAutoresizingFlexibleHeight;
[cell.contentViewaddSubview:DataLabel];
[DataLabel release];
}
UILabel *DataLabel = (UILabel *)[cell.contentViewviewWithTag:100];
[DataLabel setFont:[UIFontboldSystemFontOfSize:18]];
cell.image = [UIImage imageNamed:[NSStringstringWithFormat:@"p%d.png", path.row +1]];
DataLabel.text = [arrayobjectAtIndex:path.row];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
下面是实现点击TableView中的行的时候实现导航,导航到图片信息页。
-(void)tableView:(UITableView *)tableViewdidSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if(picShow == nil)
{
picShow = [[show alloc]initWithNibName:@"Pictures" bundle:nil];
}
[self.navigationControllerpushViewController:picShow animated:YES];
[picShow showPictures:[arrayobjectAtIndex:[indexPath row]]];
}
最后释放掉资源。
这个是我自己为了温习,学习用的。例子程序可以去我的CSDN上面下载。
http://hanyegudeng.download.csdn.net/

浙公网安备 33010602011771号