วันพฤหัสบดีที่ 9 ธันวาคม พ.ศ. 2553

UITableView (Basic)

จะเป็นการสร้าง UITableView แบบง่ายๆ ครับ
เริ่มจากสร้าง Project 
ตั้งชื่อ ผมใช้ชื่อ TableViewBasic




เลือก File TableViewBasicAppDelegate.h
เพิ่ม Protocol และ Property

Protocol
UITableViewDelegate, UITableViewDataSource

Property
UITableView *_tableView;
NSArray *_tableData;



เลือก TableViewBasicAppDelegate.m
ใน Method
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    

สร้าง UITableView
_tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 200, 400) style:UITableViewStylePlain];
_tableView.delegate = self;
_tableView.dataSource = self;
[window addSubview:_tableView];



สร้าง TableData ที่ต้องการแสดงใน TableView 

_tableData = [[NSArray alloc] initWithObjects:@"Data1", @"Data2", @"Data3", nil];



Implement UITableView Protocol สำคัญ 2 ตัว (เป็นส่วนของ UITableViewDataSource)

เป็น Method สำหรับสร้าง Cell
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"tableCell"];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"tableCell"] autorelease];
}
cell.textLabel.text = [_tableData objectAtIndex:indexPath.row];
return cell;
}
* NSIndexPath จะเก็บ Row และ Section ของ TableView

เป็น Method สำหรับบอกจำนวน Cell
-(NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section{
return [_tableData count];
}


ลอง Build And Run จะมี TableView แสดงข้อมูลใน _tableData ที่สร้างไว้

เวลา Cell ถูกเลือกจะทำงานกับ UITableViewDelegate 

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
NSLog(@"%@", [_tableData objectAtIndex:indexPath.row]);
}



เมื่อเราเลือก Cell ใน Log จะแสดงข้อมูลใน _tableData 


ไม่มีความคิดเห็น:

แสดงความคิดเห็น