更改添加的tableview单元格的背景颜色

时间:2012-03-20 18:27:58

标签: iphone uitableview

我桌面中最顶级的单元格有一个文本字段,用于向tableview添加新名称。我有它,以便添加的名称从文本字段下方动画。我想要的是让每个新单元格具有与现有单元格不同的背景颜色。

我试过

[self.tableView selectRowAtIndexPath:newIndexPath animated:YES scrollPosition:nil];

但它没有做任何事情。我认为这可能是因为新单元正在转换并且它还没有任何索引。不确定,但我知道它不起作用。来自其他地方的任何想法或例子?

--- 更新 ---

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

    TextFieldCell *customCell = (TextFieldCell *)[tableView dequeueReusableCellWithIdentifier:@"TextCellID"];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];

    if (indexPath.row == 0) {
        if (customCell == nil) {
            NSArray *nibObjects = [[NSBundle mainBundle] loadNibNamed:@"TextFieldCell" owner:nil    options:nil];
            for (id currentObject in nibObjects) {
                if ([currentObject isKindOfClass:[TextFieldCell class]])
                    customCell = (TextFieldCell *)currentObject;
            }
        }

        customCell.nameTextField.delegate = self;
        cell = customCell;
    }

    else {
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        }

        cell.textLabel.text = [[self.peopleArray objectAtIndex:indexPath.row-1] name];
    }

    return cell;
}

我添加此人的姓名:

- (void)textFieldDidEndEditing:(UITextField *)textField {

    // If the textfield isn't blank, go ahead and add the person
    if ([textField.text length] != 0) {

        // Create new person
        Person *addedPerson = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:[self context]];

        // Set person's information
        [addedPerson setName:[textField.text capitalizedString]];

        // Add the person to the beginning of the datasource array
        [self.peopleArray insertObject:addedPerson atIndex:0];

        // Get the person's name from the textfield so that I can add their name later
        TextFieldCell *textCell = [[TextFieldCell alloc] init];
        NSIndexPath *path = [NSIndexPath indexPathForRow:0 inSection:0];
        textCell = (TextFieldCell *)[self.tableView cellForRowAtIndexPath:path];

        // Set the label below the textfield to the text from the textfield above
        NSString *label = [NSString stringWithFormat:@"%@ was added", [textField text]];
        textCell.addedNameLabel.text = label;

        // Clear textfield for next entry
        textField.text = @"";

        // Animation to insert the new person at the top of the tableview
        NSIndexPath *pathInsert = [NSIndexPath indexPathForRow:1 inSection:0];
        NSArray *indexArray = [NSArray arrayWithObjects:pathInsert,nil];

        [self.tableView beginUpdates];
        [self.tableView insertRowsAtIndexPaths:indexArray withRowAnimation:UITableViewRowAnimationTop];
        [self.tableView endUpdates];

    }
}

0 个答案:

没有答案