UITableView (Basic)
วิธีทำ UITableView ใน iPhone
ใน iPhone เราจะพบ Application ที่ใช้ UITableView เป็นส่วนประกอบหลายตัว
วิธีทำในขั้นพื้นฐานก็ง่ายมากครับ
ขั้นแรกก็สร้าง UITableView แล้วกำหนด Delegate และ DataSource
_tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 300, 450) style:UITableViewStylePlain];
_tableView.delegate = self;
_tableView.dataSource = self;
สำหรับ UITableView จะมีส่วนของ Delegate และ DataSource ที่เราจำเป็นต้อง Implement ที่สำคัญ 3 ตัว
-(void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath;
Method ที่จะทำงานเมื่อเราทำการเลือก Cell ใน Table ที่เราสร้างขึ้น
-(UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath;
Method สำหรับการสร้าง Table Cell
-(NSInteger)tableView:(UITableView*)table numberOfRowsInSection:(NSInteger)section;
Method ที่จะบอกจำนวน Cell ของ Table
Example
-(void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath{
NSLog(@”%@ :: %@”, indexPath, [_tableData objectAtIndex:indexPath.row] );
}-(UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellIdentifier"];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@”cellIdentifier”] autorelease];
}
cell.textLabel.text = [_tableData objectAtIndex:indexPath.row];
return cell;
}
-(NSInteger)tableView:(UITableView*)table numberOfRowsInSection:(NSInteger)section{
return [_tableData count];
}
ในตัวอย่างจะใช้ NSArray _tableData เก็บข้อมูลของ Cell ใน Table ไว้นะครับ
เมื่อเลือกก็จะแสดง indexPath และข้อมูลออกมาครับ
*การประกาศตัวแปร การใช้ Delegate หาตัวอย่างได้ทั่วไปนะครับ (ในนี้จะไม่ได้ใส่ไว้)