2014-02-25 19 views
0

我有一個ViewControllerA包含的tableView與UITableViewStylePlain風格,就像這樣:變化的tableView風格UITableViewStyleGrouped在子類中的方法

- (void)loadView{ 
    [super loadView]; 

    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain]; 
    [self.view addSubview:self.tableView]; 
} 

現在,我有一個ViewControllerSubAViewControllerA子類,大部分邏輯是相同的與ViewControllerA,但tableView的風格應該是。什麼是我需要做的就是創建一個新的tableView與風格,使用此代碼:

- (void)loadView 
{ 
    [super loadView]; 
    [self.tableView removeFromSuperview]; 
    self.tableView = nil; 

    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped]; 
    [self.view addSubview:self.tableView]; 
} 

有沒有更好的解決方案?我不認爲要刪除舊的桌面視圖,然後創建一個新的視圖看起來不錯。

+0

它是基於ARC的項目嗎? – Rajesh

回答

1

你可以使用多態!

在基類中的代碼更改爲

- (void)loadView 
{ 
    [super loadView]; 
//..... additional code here 
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:[self getTableStyle]]; 
    [self.view addSubview:self.tableView]; 
} 

- (UITableViewStyle)getTableStyle 
{ 
    return UITableViewStylePlain; 
} 

而且在你的孩子類,你應該添加

- (UITableViewStyle)getTableStyle 
{ 
    return UITableViewStyleGrouped; 
} 

這就是所謂的「工廠法」。

+0

謝謝!這將使代碼更好。 – simalone

+0

不客氣!它被稱爲「工廠方法」。 – Avt