Пользовательская проблема с ячейкой uitableview - PullRequest
2 голосов
/ 07 октября 2010

У меня есть пользовательский UITableViewCell как таковой:

@implementation CellWithThreeSubtitles

@synthesize title, subTitle1, subTitle2, subTitle3;

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        self.textLabel.backgroundColor = self.backgroundColor;
        self.textLabel.opaque = NO;
        self.textLabel.textColor = [UIColor blackColor];
        self.textLabel.highlightedTextColor = [UIColor whiteColor];
        self.textLabel.font = [UIFont boldSystemFontOfSize:22.0];
    }
    return self;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    CGRect contentRect = self.contentView.bounds;

    CGRect frame = CGRectMake(35.0, 0, contentRect.size.width, 50.0);
    self.textLabel.frame = frame;

    UILabel *subLabel1 = [[UILabel alloc] init];
    frame = CGRectMake(35.0, 34.0, contentRect.size.width, 25.0);
    subLabel1.font = [UIFont systemFontOfSize:18.0];
    subLabel1.backgroundColor = [UIColor clearColor];
    subLabel1.text = subTitle1;
    subLabel1.opaque = NO;
    subLabel1.frame = frame;
    [self.contentView addSubview:subLabel1];

    UILabel *subLabel2 = [[UILabel alloc] init];
    frame = CGRectMake(35.0, 54.0, contentRect.size.width, 25.0);
    subLabel2.font = [UIFont boldSystemFontOfSize:18.0];
    subLabel2.backgroundColor = [UIColor clearColor];
    subLabel2.text = subTitle2;
    subLabel2.opaque = NO;
    subLabel2.frame = frame;
    [self.contentView addSubview:subLabel2];

    UILabel *subLabel3 = [[UILabel alloc] init];
    frame = CGRectMake(contentRect.size.width-100.0, 54.0, contentRect.size.width, 25.0);
    subLabel3.font = [UIFont systemFontOfSize:18.0];
    subLabel3.backgroundColor = [UIColor clearColor];
    subLabel3.text = subTitle3;
    subLabel3.opaque = NO;
    subLabel3.frame = frame;
    [self.contentView addSubview:subLabel3];

}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {

    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}


- (void)dealloc {
    [super dealloc];
    [subTitle4 release];
    [subTitle3 release];
    [subTitle2 release];
    [subTitle1 release];
    [title release];

}

Когда я реализую его в моем UITableView, например:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    int section = [indexPath indexAtPosition:0];    
    static NSString *kCustomCellID = @"AppointmentCellID";

    CellWithThreeSubtitles *cell = (CellWithThreeSubtitles *)[tableView dequeueReusableCellWithIdentifier:kCustomCellID];
    if (cell == nil) {
        cell = (CellWithThreeSubtitles *)[[[CellWithThreeSubtitles alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCustomCellID] autorelease];
    }

    switch (section) {
        case 0: 
            if ([wineArray count]==0) {
                cell.textLabel.text = @"No wine favorites selected yet";
            }else{
                cell.subTitle1 = [[wineArray objectAtIndex:indexPath.row] objectForKey:@"Varietal"];
                cell.subTitle2 = [NSString stringWithFormat:@"Bin No. %@", [[wineArray objectAtIndex:indexPath.row] objectForKey:@"Bin"]];
                cell.subTitle3 = [NSString stringWithFormat:@"$%@", [[wineArray objectAtIndex:indexPath.row] objectForKey:@"Price"]];
                cell.textLabel.text = [NSString stringWithFormat:@"%@ (%@)", [[wineArray objectAtIndex:indexPath.row] objectForKey:@"Name"], [[wineArray objectAtIndex:indexPath.row] objectForKey:@"Availability"]];
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;            
            cell.userInteractionEnabled = NO;

            break;          
        case 1: 
            if ([dinnerArray count]==0)
                cell.textLabel.text = @"No dinner favorites selected yet";
            else 
                cell.textLabel.text = [NSString stringWithFormat:@"%@", [[dinnerArray objectAtIndex:indexPath.row] objectForKey:@"Name"]];      

            break;
    }   
    return cell;
}

содержимое ячейки дублируетсяВершина самого себя каждый раз, когда ориентация устройства меняется.Это перерисовывает ячейку каждый раз, когда устройство вращается?И если так, как я могу предотвратить это?

Ответы [ 2 ]

4 голосов
/ 07 октября 2010

Вы должны создать подпредставления и добавить их в массив подпредставлений вашей ячейки в вашем методе -initWithStyle:reuseIdentifier:. Вам нужно только создать подпредставления один раз. Метод -layoutSubviews неоднократно вызывается платформой каждый раз, когда изменяется ориентация устройства, чтобы позволить вам изменять размер и / или перемещать подпредставления (плюс вносить любые другие незначительные корректировки), чтобы компенсировать различия между ориентациями.

0 голосов
/ 07 октября 2010

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

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