2011-11-14 79 views
0

因此,我需要遍歷的UITableViewControllers的廣泛層次結構。每個人都需要它自己的自定義視圖控制器。我的任何特定tableview的數據源當前是一串字符串,如「A,B,C,D,E,F」。我didSelectRowAtIndexPath方法方法是一長串if語句,像這樣的(僞):UITableViewController的自定義類Datasource

if cell.text = "A" 
    alloc init AViewController 
    navigationController push aViewController 
if cell.text = "B" 
    alloc init BViewController 
    navigationController push bViewController 

我覺得這是凌亂。必須有一個更乾淨的方式來做到這一點。任何「最佳實踐」?我最好的想法是製作一個包含cellTitle和viewController類的自定義類。然後我可以使用這些數組作爲我的數據源,並做這種事情:

UITableViewController *newView = [custom.viewControllerClass alloc] init... 

想法?

回答

2

您的頂級表視圖控制器上添加一個屬性:

@property (strong) NSDictionary *viewControllerClassForCell; 

viewDidLoad或其他初始化方法:

viewControllerClassForCell = [NSDictionary dictionaryWithObjectsAndKeys: 
    [AViewController class], @"A", 
    [BViewController class], @"B", 
    // etc. 
    nil]; 

didSelectRowAtIndexPath

Class vcClass = [self.viewControllerClassForCell objectForKey:cell.text]; 
[self.navigationController pushViewController:[[vcClass alloc] initWithNibName:nil bundle:nil] animated:YES]; 
1

您可以使用NSClassFromString()並用你的cell.text構建字符串。

像這樣的事情在你的didSelectRowAtIndexPath

NSString * className = [NSString stringWithFormat:@"%@ViewController", cell.text]; 
UIViewController * vc = [[NSClassFromString(className) alloc] init]; 
[self.navigationController pushViewController:vc] 

,或者在一個比較經典的方式,你可以有它接受的名稱作爲參數的方法,並返回選定的viewController

- (UIViewController*) viewControllerForName: (NSString*) theName { 
    if ([theName isEqualToString:@"A"]) return [[AViewController alloc] init]; 
    else if (....) 
} 
的實例

didSelectRowAtIndexPath

[self.navigationController pushViewController:[self viewControllerForName:cell.text]] 
相關問題