Подтвердить что ты не робот

Изменение цвета альтернативной строки в UITableView для iPhone SDK

В моем приложении, я хочу отображать table-table с несколькими столбцами в iPad.

Итак, я использовал элемент управления cocoa: MultiColumn TableView

он отлично работает для меня, но я хочу отображать строки в альтернативном цвете.

Для этого я не могу найти, где я меняю код для него.

Помогите решить эту проблему.

4b9b3361

Ответ 1

Попробуйте использовать это, он будет работать нормально.

- (void)tableView: (UITableView*)tableView willDisplayCell: (UITableViewCell*)cell forRowAtIndexPath: (NSIndexPath*)indexPath
{

        if(indexPath.row % 2 == 0)
              cell.backgroundColor = [UIColor redColor];
        else
              cell.backgroundColor = [UIColor whiteColor];
}

Ответ 2

используйте indexPath в cellForRowAtIndexPath, чтобы получить желаемые результаты.

    if( [indexPath row] % 2){
          cell.backgroundColor=[UIColor whiteColor];
    } 
    else{
          cell.backgroundColor=[UIColor purpleColor];
    }

У вас будет этот метод делегата в классе, который реализует UITableViewDelegate

Ответ 3

Попробуйте этот код::

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

    if (indexPath.row % 2 == 0) {
       cell.backgroundColor = [UIColor lightGrayColor];
    }
    else
    {
        cell.backgroundColor = [UIColor darkGrayColor];
    }
    .......

    return cell;
}

Надеюсь, это поможет вам.

Спасибо.

Ответ 4

Сначала вам нужно взять модули каждой строки.

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

    if (indexPath.row % 2 == 0) {
       cell.backgroundColor = [UIColor lightGrayColor];
    }
    else
    {
        cell.backgroundColor = [UIColor darkGrayColor];
    }
    ....


    return cell;
}

Ответ 5

Кто-нибудь, пытающийся сделать это быстро, вот мой код. Маленький и превосходный.

Этот трюк работает с даже статическими ячейками, где я не использую метод cellForRowAtIndexPath.

Извините за небольшой ответ. Надеюсь, вы знаете о datasource делегатам.

 override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {

    if (indexPath.row % 2) != 0{
        cell.backgroundColor = UIColor .blackColor()
    }else{
        cell.backgroundColor = UIColor .lightGrayColor()

    }

 }

Он даст вам результат, как...

Цвет каждой альтернативной ячейки в ios с помощью Swift

Спасибо

Надеюсь, что это помогло.

Ответ 6

попробуйте сделать это в

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


static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}
    if(indexPath.row%2==0)
        cell.contentView. backgroundColor=[UIColor redColor];
    else
        cell.contentView.backgroundColor=[UIColor greenColor];




return cell;


}

Ответ 8

в методе cellForRow вы должны проверить, является ли indexPath.row делимым на 2, назначить первый цвет, иначе назначить второй цвет и вернуть полученную ячейку

Ответ 9

func colorForIndex(index: Int) -> UIColor 
{
    let itemCount = stnRepos.count - 1
    let color = (CGFloat(index) / CGFloat(itemCount)) * 0.6
    return UIColor(red: 0.80, green: color, blue: 0.0, alpha: 1.0)
}

func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell,
    forRowAtIndexPath indexPath: NSIndexPath) 
{        
    if (indexPath.row % 2 == 0)
    {
        cell.backgroundColor = colorForIndex(indexPath.row)
    } else {
        cell.backgroundColor = UIColor.whiteColor()()
    }
}

Ответ 10

Для Swift 3 + и с уменьшенной непрозрачностью:

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {

        if(indexPath.row % 2 == 0) {
            cell.backgroundColor = UIColor.red.withAlphaComponent(0.05)
        } else {
            cell.backgroundColor = UIColor.white
        }
}

Ответ 11

В таком простом примере я бы выбрал троичный оператор. Я просто ненавижу видеть дубликаты cell.backgroundColor.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

.
.
.
    cell.backgroundColor = indexPath.row % 2 == 0 ? UIColor.red.withAlphaComponent(0.05) : .white
.
.
.
}

Ответ 12

вы можете запустить цикл, который будет увеличивать индекс path.row на 2, а затем в теле этого цикла u может назначить цвет.,

Ответ 13

Это рабочий код для Swift 4.x и выше

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    if(indexPath.row % 2 == 0) {
        cell.backgroundColor = UIColor.white
    } else {
        cell.backgroundColor =  UIColor.lightGray
    }
}

Удачного кодирования :)