IOS中的高级控件表视图
<UITableViewDataSource,UITableViewDelegate>
源代码如下
ViewController.h
@interface ViewController : UIViewController
<UITableViewDataSource,UITableViewDelegate>{
NSArray * listData;
NSArray * listImage;
}
@property(nonatomic,retain)NSArray * listData;
@property(nonatomic,retain)NSArray * listImage;
@end
接下来就该实现最重要的功能了
先把需要的图片COPY到工程中来
最重要要特别注意的下面的方法实现好后就可以看到最下面的效果
//这个方法里面实现对数据的初始化,创建好文字和图片位置的数组
- (void)viewDidLoad
//这个是该控件里面最为核心的代码红色的代码为模式代码,为得是不让表格加载过多而引起内存泄漏,所以达到一定程度后,只让他改变控件中的内容就行了
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
//这个方法是返回每一段中的大小
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
//这个事件为点击表格中的列实现的代码
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
下面上源代码:
ViewController.m
@implementation ViewController
@synthesize listData;
@synthesize listImage;
//实现表示图的方法
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
NSUInteger row = [indexPath row];
NSString *rowValue = [listData objectAtIndex:row];
NSString *message = [[NSString alloc] initWithFormat:@"你选择的号码是%@",rowValue];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"生死选择"
message:message delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:nil, nil];
[alert show];
[alert release];
[message release];
//实现点击时,让点击的那个选中慢慢消失
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
//返回段里面有几行
return [listData count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
NSUInteger row = [indexPath row];
cell.textLabel.text = [listData objectAtIndex:row];
UIImage *img = [UIImage imageNamed:[listImage objectAtIndex:row]];
cell.imageView.image = img;
return cell;
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSArray *arr = [[NSArray alloc] initWithObjects:@"CALL01",@"CALL02",
@"CALL03",@"CALL04",@"CALL05",@"CALL06",@"CALL07",
@"CALL08",@"CALL09",nil];
NSArray *img = [[NSArray alloc] initWithObjects:@"1.png",@"2.png",@"3.png",@"4.png",@"5.png",
@"6.png",@"7.png",@"8.png",@"9.png",nil];
self.listData = arr;
self.listImage = img;
[arr release];
[img release];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)dealloc
{
[listData release];
[listImage release];
[super dealloc];
}
@end
最后的效果