Xcode版本4.4.1
動態基本實作如下
1.開一個Project, 使用Single View Application,然後取名稱如下
2. 完成後的檔案列表,注意到MyTableViewController的Class是繼承自UIViewController
3. 我們產生一個新的UITableViewController Class檔來取代MyTableViewController.h/m,最後要選擇 Replace來取代原始檔案

4. 取代完成後,需要將Storyboard內的ViewController也換成TableViewController,如圖新增一個 TableViewController,然後將左邊原始的ViewController刪除。

6. 並且要將Class設成與MyTableViewController.m同一個
7. 完成以上基本設定後,只要在MyTableViewController.m下加入以下的程式碼,就會得到動態的TableView的效果了。(注意藍色部分)
@interface MyTableViewController ()
@end
NSArray *myData;
@implementation MyTableViewController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
myData = [[NSArray alloc] initWithObjects:@"First",@"Second",@"Third",@"Fourth",@"Fifth", nil];
// Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO;
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
#warning Potentially incomplete method implementation.
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
#warning Incomplete method implementation.
// Return the number of rows in the section.
//return 0;
return [myData count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
// Configure the cell...
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
cell.textLabel.text = (NSString *)[myData objectAtIndex:indexPath.row];
return cell;
}
8.這是額外加的效果,當你按了某個Item,就會出現相關的訊息。
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSUInteger row = [indexPath row];
NSString *rowValue = [myData objectAtIndex:row]; //用 NSString 去記錄使用者點選的 row
NSString *message = [[NSString alloc] initWithFormat:@"你選擇了 %@",rowValue];
//用一個 alert 去告訴使用者現在正在點選的 Row
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"展示結果" message:message delegate:nil cancelButtonTitle:@"結束" otherButtonTitles:nil];
[alert show];
//[message release];
//[alert release];
//讓選取的效果消失
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}






沒有留言:
張貼留言