2015-11-02 44 views
1

我用的tableview的第一個單元格像頭,例如在cellForRowAtIndexPath使用的TableView第一個細胞作爲標題和問題

if indexPath.row == 0 { 
cell.label.text = "Header" 

}else { 

// fill up the data 
cell.label.text = array[indexPath.row] 
} 

而在numberOfRowsInSection我回到這一點:

return array.count 

可以說我有20個元素在我的數組中,我保留了第一個單元格作爲標題,因此其中一個元素將被刪除。如果我增加了array.count + 1array[indexPath.row + 1]來解決問題,所以我得到數組越界。我只想使用第一個單元格作爲標題,並在下一個20格中使用其餘的數據。爲什麼不能發生這種事情!

回答

2

我想你想用array[indexPath.row - 1]

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    if indexPath.row > 0 { 
     let entry = array[indexPath.row - 1] 
    } else { 
     //Configure the placeholder cell 
    } 
} 
1

你應該把一個佔位符,您的陣列的頭球,那麼array.count將包括標題,佔位符可以是指數隨indexPath.row正確,所以你不會得到一個出界失誤

否則如果那不是一個選項,你將有你的索引數組時破例,所以像

//psuedo code 
if (indexPath.row == 0) { 
    return headerCell; 
} 
else { 
    data = array[indexPath.row-1]; 

    return normalCell; 
} 
1

後得到的數據,你應該建立在你的數據的標題的空對象。

[array insertObject:@"header" atIndex:0];

0

恕我直言,這將是更容易得到你的數組的第一個元素,創建自定義標題視圖,並從你的陣列將其取下,你只需要用數組中的東西來處理普通的'uitableviewcells',你不需要使用任何條件。有一個'委託',您可以在其中設置'uitableviewheader',這也應該放在哪裏。

0

爲此,您可以在兩種類型

首先是

if (indexPath.row == 0) 
{ 
    cell.textLabel.text = @"Header"; 
} 
else { 
    cell.textLabel.text = array[indexPath.row - 1]; 
    NSLog(@"The cell index is - %@",array[indexPath.row - 1]); 
} 

二是

if (indexPath.row > 0) 
{ 
    cell.textLabel.text = array[indexPath.row - 1]; 
    NSLog(@"The cell index is - %@",array[indexPath.row - 1]); 
} 
else 
{ 
    cell.textLabel.text = @"Header"; 
} 
相關問題