2016-10-17 50 views
-2

我想改變細胞色在每個細胞中(4個色%4):iOS的變化的每一個細胞的顏色(節+行)

1第1節

小區1:RED

小區2:BLUE

2.第2

細胞3:BLACK

3.第3

細胞4:WHITE

4.第4

細胞5:RED

細胞6:BLUE

細胞7 :黑色 ...

我該如何做到這一點?

我知道如何改變顏色cellForRowcell.contentView.backgroundColor = [UIColor colorWithRed:119.0/255.0 green:221.0/255 blue:167.0/255 alpha:1.0f];

+0

是否有超過7個單元格,或者是一個設定的數量? – BJHStudios

+0

@BJHStudios等於或多於或少於7個單元 – Viny76

+0

我從問題描述中瞭解到,您需要的是序列中的背景顏色,即紅色,藍色,黑色,白色等,而不管該部分如何,對吧?你正在使用哪種語言? – Adeel

回答

0

你可以有一個開關的情況下statment來解決這一問題

創建一個函數來回報給你一個UIColor,並作爲該方法的參數,則發送從0到3的數

-(UIColor *)colorForCell:(NSInteger)index { 
    switch (index) { 
       case 0: 
        return RED 
        break; 
       case 1: 
        return BLUE 
        break; 
       case 2: 
        return BLACK 
        break; 
       case 3: 
        return WHITE 
        break; 

       default: 
        return RED 
        break; 
      } 
} 

,並不僅僅是做cellForRow : cell.contentView.backgroundColor = [self colorForCell:index]

+0

不起作用。嘗試[self colorForCell:indexPath.row] - >需要給NSUInteger – Viny76

1

我假設你有一個數組存儲你的部分和行數據。我想創建一個函數,它接受一個部分和行號作爲參數,並返回忽略部分的位置:

- (Int) getPosition:(Int) section rowNumber:(Int) row { 
    int position = 0; 
    for (int i = 0; i < section; i++) { 
     position += DataArray[i].count; 
    } 
    return position + row; 
} 

這將增加了所有的罪名在前面的章節中,再加入該行的當前部分,給你一個新的號碼用於着色。然後調用它,在你cellForRow方法寫:

newIndex = [self getPosition:indexPath.section rowNumber:indexPath.row] 

如果你使用這個號碼來確定顏色,它會被正確着色。

+0

不能成功實現Objective-C – Viny76

+0

我編輯了我的迴應,以我最好的嘗試在objective-c。你可以把這個函數放在你的tableViewController類中,然後從你的cellForRowAt方法中調用它來得到一個絕對索引,而不管該部分。 –

+0

好吧,之後,我要在cellForRow中調用什麼? – Viny76

0

找到解決方案:

NSInteger rowNumber = 0; 
for (NSInteger i = 0; i < indexPath.section; i++) { 
    rowNumber += [self.tableView numberOfRowsInSection:i]; 
} 

rowNumber += indexPath.row; 
switch (rowNumber % 4) { 
    case 0: 
     cell.contentView.backgroundColor = [UIColor blackColor]; 
     break; 
    case 1: 
     cell.contentView.backgroundColor = [UIColor redColor]; 
     break; 
    case 2: 
     cell.contentView.backgroundColor = [UIColor whiteColor]; 
     break; 
    case 3: 
     cell.contentView.backgroundColor = [UIColor yellowColor]; 
     break; 

    default: 
     break; 
} 
0

既然你要選擇基於細胞不論節的索引/位置的序列中的問題中提到的四種顏色之一,所以這會爲你做。

- (UIColor *)colorForCellAtIndexPath:(NSIndexPath *)indexPath { 

UIColor *cellColor; 
NSInteger index = 0; 

for (NSInteger i=0; 1<indexPath.section; i++) { 

    index += [self.tableView numberOfRowsInSection:i]; 
} 

index += indexPath.row; 

switch (index % 4) { 

    case 0: 
     cellColor = [UIColor redColor]; 
     break; 

    case 1: 
     cellColor = [UIColor blueColor]; 
     break; 

    case 2: 
     cellColor = [UIColor blackColor]; 
     break; 

    case 3: 
     cellColor = [UIColor whiteColor]; 
     break; 

    default: 
     break; 
} 

return cellColor; 
} 

調用此方法在您的cellForRowAtIndexPath:並通過indexPath作爲參數。