Определите indexPath для подкласса UITableViewCell, чтобы я мог указать выравнивание моей UILabel - PullRequest
0 голосов
/ 04 августа 2011

Я подклассифицирую uitableviewcell, чтобы я мог применить стандартный фон и текст для всех своих ячеек, это моя первая попытка, но я в основном показываю, как мне хотелось бы. Хотя я застрял на одном вопросе. В моей таблице две группы, и я хотел бы, чтобы первая группа была центрирована по тексту, и я хотел бы, чтобы вторая группа была выровнена по левому краю. Но на данный момент нет такой удачи.

CustomCell.m

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {

NSIndexPath *indexPath = [(UITableView *)self.superview indexPathForCell: self];
NSLog(@"%i", indexPath);
int rows = [(UITableView *)self.superview numberOfRowsInSection:indexPath.section];
NSLog(@"%i", rows);

if ((self = [super initWithStyle:style reuseIdentifier:reuseIdentifier])) {

    if (centerText) {
        cellText = [[[UILabel alloc] initWithFrame:CGRectMake(0, 15, self.bounds.size.width - 10, 30)] autorelease];
        cellText.textAlignment = UITextAlignmentCenter;
    }else {
        cellText = [[[UILabel alloc] initWithFrame:CGRectMake(20, 15, self.bounds.size.width - 10, 30)] autorelease];
        cellText.textAlignment = UITextAlignmentLeft;
    }

    cellText.font = [UIFont boldSystemFontOfSize:16];
    cellText.backgroundColor = [UIColor clearColor];
    cellText.shadowColor = [UIColor colorWithWhite:1.0 alpha:0.5];
    cellText.shadowOffset = CGSizeMake(0,1);
    cellText.textColor = [UIColor colorWithRed:0x4c/255.0 green:0x4e/255.0 blue:0x48/255.0 alpha:1.0];



    UIImageView *imgView = [[UIImageView alloc] initWithFrame:self.frame];
    UIImage* img = [UIImage imageNamed:@"odd_slice.png"];
    imgView.image = img;
    self.backgroundView = imgView;
    [imgView release];

    UIImage *accessoryImage = [UIImage imageNamed:@"content_arrow.png"];
    UIImageView *accessoryView = [[UIImageView alloc] initWithImage:accessoryImage];
    //  accessoryView.image = accessoryImage;
    self.accessoryView = accessoryView;
    [accessoryView release];


    //Selected State
    UIImage *selectionBackground = [UIImage imageNamed:@"row_selected.png"];
    UIImageView *selectionView = [[UIImageView alloc] initWithFrame:self.frame];
    selectionView.image = selectionBackground;
    self.selectedBackgroundView = selectionView;
    [selectionView release];

    //Adds Text
        [self addSubview:cellText];
    }
    return self;
}

TableView.m

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

CoCoachAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSArray *keys = [[appDelegate rowersDataStore] allKeys];

static NSString *CellIdentifier = @"Cell";

CustomCell *cell = (CustomCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {

    switch (indexPath.section) {
        case 0:
            [cell setCenterText:YES];
            break;
        case 1:
            [cell setCenterText:NO];
            break;

        default:
            break;
    }


    cell = [[[CustomCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}

switch (indexPath.section) {
    case 0:
        [cell.cellText setText:@"Create New Rower"];            
        break;
    case 1:
        [cell.cellText setText:[keys objectAtIndex:indexPath.row]];
        break;

    default:
        break;
}
    // Set up the cell...
    return cell;
}

У кого-нибудь есть предложения?

1 Ответ

2 голосов
/ 04 августа 2011

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

Это код, который не имеет смысла:

if (cell == nil) {

    switch (indexPath.section) {
        case 0:
            [cell setCenterText:YES];
            break;
        case 1:
            [cell setCenterText:NO];
            break;

        default:
            break;
    }

    cell = [[[CustomCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}

Вы получаете клетку. Если он не существует, то вы устанавливаете центрирование (которое ничего не делает; помните, cell равно nil). Затем вы создаете его.

Но что вы действительно хотите сделать, это установить центрирование после того, как вы получили или создали ячейку. Тебе все равно, как ты это получишь; Вы просто хотите перенастроить его на текущие значения.

CustomCell *cell = (CustomCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[CustomCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}

switch (indexPath.section) {
    case 0:
        [cell setCenterText:YES];
        [cell.cellText setText:@"Create New Rower"];            
        break;
    case 1:
        [cell setCenterText:NO];
        [cell.cellText setText:[keys objectAtIndex:indexPath.row]];
        break;

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