2011-12-25 131 views
0

我正在嘗試將2 UITableView添加到我的UIViewController。我需要爲這些表添加不同的數據。將數據添加到2個表

這是我加入2個表(這個代碼加入到viewDidLoad方法)

self.tableView2 = [[UITableView alloc] initWithFrame:CGRectMake(0,140,292,250) style:UITableViewStylePlain] ; 
self.tableView2 .dataSource = self; 
self.tableView2 .delegate = self; 

那麼其他表

self.tableView1 = [[UITableView alloc] initWithFrame:CGRectMake(0,0,320,100) style:UITableViewStylePlain] ; 
self.tableView1 .dataSource = self; 
self.tableView1 .delegate = self; 

定義如下部分的數量;

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    if (tableView==tableView1) { 
     return 12; 
    } 
    else { return 10; } 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    // ...... more code here 
    if (tableView == self.tableView1) {  
     if (cell == nil) { 
      cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];   
     } 
     cell.selectionStyle = UITableViewCellSelectionStyleNone; 
     [email protected]"Cells .... "; 
    } 
    else{ 
     // the remaining code here.. i am populating the cell as in the previous `IF` condition. 
    } 
} 

問題是,我只得到第一個表填充,而不是第二個表。爲什麼是這樣?我該如何解決這個問題?

編輯: 我還添加以下代碼,希望作出改變

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    if (tableView==tableView1) { 
     return 1; 
    } 
    else if (tableView==tableView2) { return 0; } 
    else { return 0; } 
} 
+0

您是如何的tableViews添加到上海華? – vikingosegundo 2011-12-25 15:07:20

+0

呃..我根據上面的代碼做了。並顯示出來。我無法填充它。需要幫助! – Illep 2011-12-25 15:08:54

+0

肯定可以確定你在else部分返回任何東西嗎? – 2011-12-25 15:18:21

回答

3

儘量遵循爲了使具有相同delegatedataSource兩個表視圖這些步驟。

  1. 設置你的表視圖,並在這兩個值#define常數tag財產。這使得代碼一致。

  2. 在您在視圖控制器子類中實現的委託和數據源方法中,根據您定義的常量測試tag屬性值。

  3. 不要爲表視圖返回0節,它根本不會顯示任何單元格。

因此,舉例來說:

#define TV_ONE 1 
#define TV_TW0 2 

// setting the tag property 
self.tableView1 = [[UITableView alloc] 
        initWithFrame:CGRectMake(0,0,320,100) 
          style:UITableViewStylePlain]; 
self.tableView1.tag = TV_ONE; 
self.tableView1.dataSource = self; 
self.tableView1.delegate = self; 
// the same for tableView2 using TV_TWO 

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { 
    if (tableView.tag == TV_ONE) { 
     return 1; 
    } 
    else if (tableView.tag == TV_TWO) { 
     return 1; // at least one section 
    } 
    else { return 0; } 
}