После того, как строка выбрана в табличном представлении, как я могу получить доступ к строкам, не выбрав текстовую метку, чтобы изменить ее цвет - PullRequest
1 голос
/ 30 июля 2011

После отображения табличного представления и выбора строки я хочу изменить цвет всех текстовых меток таблицы с невыбранными строками на синий.в этом случае я не знаю, как получить доступ к текстовой метке других строк.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{ 
    switch (indexPath.row) {
        case 0:
          UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
          cell.textLabel.textColor = [UIColor yellowColor];
          //******* NEED TO CHANGE ALL OTHER ROWS TEXT LABEL TO BLUE
          break;
        case 1:
          UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
          cell.textLabel.textColor = [UIColor yellowColor];
          //******* NEED TO CHANGE ALL OTHER ROWS TEXT LABEL TO BLUE 
          break;
        default:
          break;
    }
}

Ответы [ 4 ]

2 голосов
/ 30 июля 2011

Управление состоянием выбора ячеек из делегата табличного представления будет излишне трудным.Вы можете сохранить путь индекса выбранной ячейки, вызвать метод cellForRowAtIndexPath: табличного представления, чтобы получить ранее выбранную ячейку, и сбросить цвет метки.Однако вы не знаете, что ранее выбранная ячейка даже видна или загружена.

Лучше использовать подкласс UITableViewCell, который реализует setSelected: для обновления своего собственного представления.Таким образом, вашему представителю табличного представления нужно только установить выбранное свойство ячейки, и ячейка отвечает за надлежащее обновление своего собственного представления.Это также позволит вам реализовать perpareForReuse для сброса представлений ваших ячеек, чтобы вам не пришлось беспокоиться о повторном использовании ранее выбранной ячейки и неожиданном отображении ячейки в выбранном состоянии.

1 голос
/ 30 июля 2011

Сохраняйте переменную, например NSInteger, называемый selectedCell, который отслеживает выбранную ячейку. Измените его на выбранную ячейку, а затем перезагрузите видимые ячейки. В tableView:cellForRowAtIndexPath: вы проверяете переменную и соответственно стилируете метку.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    selectedCell = indexPath.row;
    [tableView reloadData];
}

Таким образом, в tableView:cellForRowAtIndexPath:

// format the cell...
if (indexPath.row==self.selectedCell) {
    // style your cell for selected state
}
else {
    // style your cell for non-selected state
}

Приветствия
Sascha

0 голосов
/ 12 июля 2013
`- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = (UITableViewCell*)[tableView dequeueReusableCellWithIdentifier:@"CellIdentifier"];
    if (nil==cell)
    {
        cell = [[[UITableViewCell alloc]  initWithFrame:CGRectMake(0,0,0,0)] autorelease];
        cell.contentView.backgroundColor=CLEAR_COLOR;
        //Configure cell format for the tableView,
        //Same format for all the three sections.
        int tagCount = 1;
        CGFloat lXCoord = 5,lYCoord = 7,lWidth = 100/*,lHeight = 18*/;
//      for (tagCount = 1; tagCount <= 1; tagCount++) {
            UILabel *lUILabel = [[UILabel alloc]init];
                lUILabel.frame = CGRectMake(lXCoord+10, 0, lWidth, 34);
            lUILabel.backgroundColor = [UIColor clearColor];
            lUILabel.textColor = RGB_A(35, 30, 32, 1);
           lUILabel.highlightedTextColor=WHITE_COLOR;
            lUILabel.font = FONT_OPENSANS_REGULAR(14);
            [cell.contentView addSubview:lUILabel];
            [lUILabel setTag:tagCount];
            RELEASE_NIL(lUILabel);
//      }
        UIImageView *lUIImageView = [[UIImageView alloc]init];
            lUIImageView.frame = CGRectMake(lXCoord+100, lYCoord, 45, 29);
       [lImageView_ setHighlightedImage:[UIImage imageNamed:[NSString stringWithFormat:@"iPad_BuildInspectionDetails_%@_Selected.png",[[mDamageTableArray_ objectAtIndex:0] objectAtIndex:indexPath.row]]]];
      [lImageView_ setImage:[UIImage imageNamed:[NSString stringWithFormat:@"iPad_BuildInspectionDetails_%@_Normal.png",[[mDamageTableArray_ objectAtIndex:0] objectAtIndex:indexPath.row]]]];
        cell.accessoryView=lUIImageView;
        [lUIImageView setTag:tagCount + 1];
        RELEASE_NIL(lUIImageView);
        UIView *lSelectedView_ = [[[UIView alloc] init] autorelease];
        lSelectedView_.backgroundColor =SELECTED_CELL_COLOR_GM;
        cell.selectedBackgroundView = lSelectedView_;
    }
    //cell.accessoryType=UITableViewCellAccessoryNone;
    return cell;
}
 - Note :-
 Use setHighlightedImage property for UIImageView `enter code here`& highlightedTextColor for UILabel.
 you can see highlighted image and highlighted text color if you select a row in UITableView
This will help you.
Happy Coding...`
0 голосов
/ 10 июля 2013
- (void)tableView:(UITableView *)tableView 
     didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

  [self setSelectedImageAndTextColorForTableCell:indexPath :tableView];
}

//THIS METHOD IS USED TO RESET THE SELECTED COLORS FOR UIIMAGEVIEW AND UILABEL------
- (void)setSelectedImageAndTextColorForTableCell:(NSIndexPath *)aIndexPath 
               :(UITableView *)aTableView {
    if (!self.LastIndexPath_) {
        if (aTableView == mTableView_) {
            [self setLastIndexPath_:aIndexPath];
        }
    }
    if (self.mLastIndexPath_.row != aIndexPath.row) {
        //If Old Cell.

      UITableViewCell *lOldCell = [aTableView cellForRowAtIndexPath:self.mLastIndexPath_];
      UILabel *lLabel_=(UILabel*)[lOldCell.contentView viewWithTag:1];
      [lLabel_ setTextColor:RGB_A(35, 30, 32, 1)];

      //If User touches on new cell.

      UITableViewCell *lNewCell = [aTableView cellForRowAtIndexPath:aIndexPath];
      UILabel *lLabel_ = (UILabel*)[lNewCell.contentView viewWithTag:1];
      [lLabel_ setTextColor:[UIColor whiteColor]];
      self.mLastIndexPath_ = aIndexPath;


    }else {
        UITableViewCell *lNewCell = [aTableView cellForRowAtIndexPath:aIndexPath];
        if (aTableView == mTableView_) {
            UITableViewCell *lNewCell = [aTableView cellForRowAtIndexPath:aIndexPath];
            UILabel *lLabel_ = (UILabel*)[lNewCell.contentView viewWithTag:1];
            [lLabel_ setTextColor:[UIColor whiteColor]];
            self.mLastIndexPath_ = aIndexPath;
        }
    }
}

Надеюсь, это поможет вам. Счастливое кодирование

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...