如何用不同的UITextField覆盖UITextField

问题描述:

我有一个在xib中定义的UITableViewCell。 这个UITableViewCell有一个名为itemText的UITextField。 这个UITableViewCell也是格式化的。如何用不同的UITextField覆盖UITextField

在表格中的所有单元格中,我希望按照xib中定义的UITextField。

但是,在一个单元格中,我想使用不同的UITextField,我使用编程方式定义,名为FinanceTextField。

在我用下面的行cellforindexpath方法:

cell.itemText = [[[FinanceTextField alloc] initWithFrame:CGRectMake(0, 0, 300, 50)] autorelease]; 

它不工作?为什么?

创建两个UITableViewCell类。一个用于你平时的观点,一个有FinanceTextField。从xibs中加载它们。在您的cellForIndexPath中,确定要使用哪个单元格,并加载(并重新使用)适当的类型。即使只有一个单元格使用不同的单元格,它也会工作。实际上,您可以在同一个表中使用所有不同类型的单元格,即行中的所有行列式,例如具有常规标签文本的第一行,具有文本字段的第二行,具有按钮的第二行等。

有一个示例项目可以帮你做到这一点。苹果开发者网站上的“食谱”示例。以下是你可能会感兴趣的代码的一部分:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
UITableViewCell *cell = nil; 

// For the Ingredients section, if necessary create a new cell and configure it with an additional label for the amount. Give the cell a different identifier from that used for cells in other sections so that it can be dequeued separately. 
if (indexPath.section == INGREDIENTS_SECTION) { 
    NSUInteger ingredientCount = [recipe.ingredients count]; 
    NSInteger row = indexPath.row; 

    if (indexPath.row < ingredientCount) { 
     // If the row is an ingredient, configure the cell to show the ingredient name and amount. 
     static NSString *IngredientsCellIdentifier = @"IngredientsCell"; 
     cell = [tableView dequeueReusableCellWithIdentifier:IngredientsCellIdentifier]; 
     if (cell == nil) { 
      // Create a cell to display an ingredient. 
      cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:IngredientsCellIdentifier] autorelease]; 
      cell.accessoryType = UITableViewCellAccessoryNone; 
     } 
     Ingredient *ingredient = [ingredients objectAtIndex:row]; 
     cell.textLabel.text = ingredient.name; 
     cell.detailTextLabel.text = ingredient.amount; 
    } else { 
     // If the row is not an ingredient the it's supposed to add an ingredient 
     static NSString *AddIngredientCellIdentifier = @"AddIngredientCell"; 
     cell = [tableView dequeueReusableCellWithIdentifier:AddIngredientCellIdentifier]; 
     if (cell == nil) { 
     // Create a cell to display "Add Ingredient". 
      cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:AddIngredientCellIdentifier] autorelease]; 
      cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; 
     } 
     cell.textLabel.text = @"Add Ingredient"; 
    } 

这仅仅是一个演示了如何创建不同的标识符项目的一部分。从这里你可以自己得到它...