UITableView是iPhone中比较常用的,用的比较多的控件,下面我们使用UITableView创建一个简单的表格,效果如下:
如果需要响应用户单击的话,需要增加UITableViewDelegate协议。
2、在ViewController.h中增加UITableViewDataSource和UITableViewDelegate协议,如下:
#import <UIKit/UIKit.h> @interface ViewController : UIViewController<UITableViewDataSource, UITableViewDelegate> { NSArray * listData; @property ( nonatomic, retain) NSArray *listData; @end 3、往列表中增加数据,实现UITableViewDataSource协议,如下:
4、响应用户单击事件,实现UITableViewDelegate协议,如下:
6、完整的代码如下: [cpp] #import "ViewController.h" @interface ViewController () @end @implementation ViewController @synthesize listData; - (void)viewDidLoad { self.listData =[[NSArray alloc] initWithObjects:@"Item1",@"Item2",@"Item3", @"Item4", @"Item5", @"Item6", @"Item7",nil];; [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. } - (void)viewDidUnload { self.listData = nil; [super viewDidUnload]; // Release any retained subviews of the main view. } - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown); } #pragma mark - Table view data source delegate //返回总行数 -(NSInteger ) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger )section { return [ self.listData count ]; } // 添加每一行的信息 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { NSString *tag=@"tag"; UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:tag]; if (cell==nil ) { cell=[[[ UITableViewCell alloc ] initWithFrame : CGRectZero reuseIdentifier:tag] autorelease]; } NSUInteger row=[indexPath row]; //设置文本 cell.text =[listData objectAtIndex :row]; //选中后的颜色又不发生改变,进行下面的设置 //cell.selectionStyle = UITableViewCellSelectionStyleNone; //不需要分割线 //tableView.separatorStyle=UITableViewCellSeparatorStyleNone; return cell; } #pragma mark - Table view data delegate //响应用户单击事件 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ UIAlertView* showSelection; NSString* message; message = [[NSString alloc]initWithFormat:@"You chose the : %@", [self.listData objectAtIndex:indexPath.row]]; showSelection = [[UIAlertView alloc] initWithTitle:@"Selected" message:message delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; [showSelection autorelease]; [showSelection show]; } |
|