iPhone:在同一个tableView中使用UITableViewCellStyleValue1和UITableViewCellStyleValue2

时间:2011-01-04 19:31:17

标签: iphone cocoa-touch uitableview

在同一个tableView中同时使用UITableViewCellStyleValue1和UITableViewCellStyleValue2的最佳方法是什么?我不确定最好的方法,因为我在切换之前使用initWithStyle:

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];

    }

    if (indexPath.section == 0) {
        switch (indexPath.row) {
            case 0:
                cell.textLabel.text = @"Username";

                break;
            case 1: 
                cell.textLabel.text = @"Password";
                break;
        }//end switch

    } else if (indexPath.section == 1) {
        switch (indexPath.row) {
            case 0: 
                cell.textLabel.text = @"Create Account";

                break;
        }//end switch
    }

    return cell;

}//end

如何在“创建帐户”单元格中使用UITableViewCellStyleValue2?

2 个答案:

答案 0 :(得分:1)

为什么不在开关内移动initWithStyle?如果你想节省一些空间并且你需要Value2与Value1相比很少,那么你可以在切换之前离开initWithStyle,然后在switch中为Value2风格的单元格再次创建它。

答案 1 :(得分:1)

在调用initWithStyle之前确定单元格样式和标识符。

您需要为每个样式使用不同的单元格重用标识符,因为如果样式为Value1的单元格被排队,您不希望将其重新用于需要样式值为Value2的行。

static NSString *CellIdentifierValue1 = @"CellIdentifierValue1";
static NSString *CellIdentifierValue2 = @"CellIdentifierValue2";

//default settings...
NSString *reuseIdentifier = CellIdentifierValue1;
UITableViewCellStyle cellStyle = UITableViewCellStyleValue1;

if ((indexPath.section == 1) && (indexPath.row == 0))
{
    //special settings for CreateAccount...
    reuseIdentifier = CellIdentifierValue2;
    cellStyle = UITableViewCellStyleValue2;
}

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
if (cell == nil)
{
    cell = [[[UITableViewCell alloc] initWithStyle:cellStyle reuseIdentifier:reuseIdentifier] autorelease];
}

//rest of existing code...
相关问题