2011-06-29 48 views
7

的tableview委託方法我有一個類內部的實現代碼如下這些委託方法:IOS:兩個實現代碼如下

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { 
return 1; 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 

return [array1 count]; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 


static NSString *CellIdentifier = @"Cell"; 

UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
if(cell == nil){ 
    cell = [[[UITableViewCell alloc]initWithStyle:UITableViewStylePlain reuseIdentifier:CellIdentifier] autorelease] ; 
} 

cell.textLabel.text = [array1 objectAtIndex:indexPath.row]; 

return cell; 
} 

,如果我有一個單一的UITableView它的確定,但如果我有兩個的UITableView?我如何組織我的代碼?帶標籤?

回答

13

看看他們中的所有委託方法如何有tableView:(UITableView *)tableView

您可以定義在頭文件中的表格視圖,然後只是簡單的去:(假設你的表稱爲myTable

if (tableView == myTable) 

然後你可以有很多意見表,只要你喜歡。

因此,例如:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 

return [array1 count]; 
} 

變爲:

的那些方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
    if (tableView == myTable) 
    { 
     return [array1 count]; 
    } 
    if (tableView == myTable2) 
    { 
     return [array2 count]; 
    } 

    return 0; 
} 
0

每個傳遞到該調用它表視圖的參考。我通常將每個表連接到接口構建器中的插座,並根據與委託方法和插座名稱中的tableView的比較有條件地返回數據源。用標籤來做也是可能的,但在編輯視圖結構時更復雜,更容易出現複雜情況。

3

我的建議是讓您的數據源充當表視圖委託,而不是您的控制器。

這是一個更接近模型 - 視圖 - 控制器模式的設計,它將允許您更靈活,並避免檢查代理方法中參數tableView的具體值。

在你的情況下,你的委託/數據源將是類型爲NSArray的成員,同時也實現UITableViewDelegate協議。

1

是的,你可以用標籤來做。給你的UITableViews標籤1和2

設立一個開關:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

static NSString *CellIdentifier = @"Cell"; 

UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
if(cell == nil){ 
    cell = [[[UITableViewCell alloc]initWithStyle:UITableViewStylePlain reuseIdentifier:CellIdentifier] autorelease] ; 
} 

switch ([tableView tag]) { 
    case 1:{ 
    [[cell textLabel] setText:@"First tag"] 
    break; 
    } 
    case 2:{ 
    [[cell textLabel] setText:@"Second tag"] 
    break; 
    } 
    default: 
    break; 
} 

return cell; 
} 
+0

標籤的尼斯用途,所以就好辦多表 – Vincent