標籤:des style blog color os io ar for 2014
功能:建立一個列表,用數組填充表格,並支援挑選清單行
//// main.m// Hello//// Created by lishujun on 14-8-28.// Copyright (c) 2014年 lishujun. All rights reserved.//#import <UIKit/UIKit.h>// 視圖控制器對象@interface HelloWorldViewController : UIViewController<UITableViewDataSource, UITableViewDelegate>{ NSArray *array; UITableView *tableView; //不用@property聲明,就不能用self進行引用? 有什麼差異,我得弄清楚}@end@implementation HelloWorldViewController-(HelloWorldViewController *) init{ array = [[NSArray alloc]initWithObjects:@"oops", @"hello", @"world", nil]; return self;}-(void) loadView{ // 建立視圖對象 UIView *contentView = [[UIView alloc]initWithFrame:[[UIScreen mainScreen] applicationFrame]]; contentView.backgroundColor = [UIColor lightGrayColor]; self.view = contentView; // 建立tableView tableView = [[UITableView alloc]initWithFrame:[[UIScreen mainScreen] applicationFrame]]; [tableView setDataSource:self]; [tableView setDelegate:self]; // tableView加入到內容視圖 [contentView addSubview:tableView];}// --------DataSource介面必須實現的方法,用於填充表格------------(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView{ return 1; //設定列表分區個數}-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ return [array count]; //設定列表長度}-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ // 產生列表單元(儘可能複用已有單元) static NSString *simpleTableIdentifer = @"SimpleTableIdentifer"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifer]; if (cell == nil) { cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifer]; } cell.textLabel.text = array[indexPath.row]; return cell;}// ----------實現Delegate介面的方法,用於操作----------------(NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath{ // 行選中之前的事件,下面代碼實現是實現取消第一行的選擇,即不允許選擇 if(indexPath.row == 0) { return nil; } else { return indexPath; }}-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ //行選中事件 NSString *rowValue = array[indexPath.row]; [tableView deselectRowAtIndexPath:indexPath animated:YES]; //取消選中狀態 NSLog(@"%@", rowValue); }@end// 委派物件@interface HelloWorldAppDelegate : NSObject <UIApplicationDelegate>{ IBOutlet UIWindow *window;}@property (nonatomic, retain) UIWindow *window;@end@implementation HelloWorldAppDelegate@synthesize window;-(void) applicationDidFinishLaunching:(UIApplication *)application{ self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen]bounds]]; HelloWorldViewController *viewController = [[HelloWorldViewController alloc]init]; self.window.rootViewController = viewController; [self.window makeKeyAndVisible];}@end// 程式入口int main(int argc, char * argv[]){ @autoreleasepool { return UIApplicationMain(argc, argv, nil, @"HelloWorldAppDelegate"); }}
iOS:實現表格填充和選擇操作