UITableView 例子一

本文转自 http://www.999dh.net/article/iphone_ios_art/31.html  转帖请注明,谢谢!

UITableView 相当于我们在 android或者windows中使用的listview,其实表述的内容是一样的,只是名字不一样而已。

1.在.h文件中实现如下
@interface CRViewController : UIViewController<UITableViewDelegate,UITableViewDataSource>
{
    NSArray * listData;
    NSArray * listImg;
}

@property(retain,nonatomic) NSArray * listData;
@property(retain,nonatomic) NSArray * listImg;

其中实现了2个委托,以及一个存放字符串,一个存放图片的NSArray

2..m文件实现如下:

@synthesize listImg;
@synthesize listData;


-(NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section
{
    return [listData count];
}

-(UITableViewCell*) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * cellID = @"cellID";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    
    if( cell == nil )
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellID]autorelease];
    }
    
    
    NSUInteger row = [indexPath row];
    cell.textLabel.text = [listData objectAtIndex:row];//主要文字
    
    UIImage * img = [UIImage imageNamed:[listImg objectAtIndex:row]];
    cell.imageView.image = img;//图片
    
    cell.detailTextLabel.text = @"www.999dh.net";//注视文字
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;//右边的小箭头
    
    return cell;
}

//点击某一行的时候会触发的函数
-(void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSUInteger row = [indexPath row];
    NSString * strText = [ listData objectAtIndex:row];
    NSString * msg =  [[NSString alloc] initWithFormat:@"selected:%@",strText];
    
    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"YES" message:msg delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    
    [alert show];
    
    [msg release];
    [alert release];
}


-(void)dealloc
{
    [listImg release];
    [listData release];
    
    [super dealloc];
}

- (void)viewDidLoad
{
    
    NSArray * array = [[NSArray alloc]initWithObjects:@"中国",@"日本",@"巴基斯坦",@"阿拉伯联合酋长国",@"美国",@"大不列颠",@"南非",@"印度", nil];
    
    NSArray * image = [[NSArray alloc]initWithObjects:@"1.png",@"1.png",@"1.png",@"1.png",@"1.png",@"1.png",@"1.png",@"1.png", nil];
    
    self.listData = array;
    self.listImg = image;
    
    [array release];
    [image release];
    
    
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    
    self.listData =nil;
    self.listImg  =nil;
}

原文地址:https://www.cnblogs.com/rollrock/p/2795926.html