Как перезаписать UITextField другим UITextField - PullRequest
3 голосов
/ 27 ноября 2011

У меня есть UITableViewCell, определенный в xib.Этот UITableViewCell имеет UITextField, называемый itemText.Этот UITableViewCell также иначе отформатирован.

Во всех моих ячейках таблицы я хотел бы использовать UITextField, как определено в xib.

Однако в одной ячейке я хотел бы использовать другуюUITextField, который я определил программно, называется FinanceTextField.

В методе cellforindexpath я использовал следующую строку:

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

Это не работает?Почему?

1 Ответ

1 голос
/ 27 ноября 2011

Создайте два класса UITableViewCell.Один для вашего обычного просмотра, тот, который имеет FinanceTextField.Загрузите их обоих из XIBS.В вашем cellForIndexPath определите, какую ячейку вы хотите использовать, и загрузите (и повторно используйте) соответствующий тип.Даже если только одна ячейка использует другую ячейку, все будет работать.Фактически, вы можете иметь все различные типы ячеек в одной и той же таблице, все определяющие в строке, такие как первая строка с обычным текстом метки, вторая с текстовым полем, третья с кнопкой и т. Д.

Есть пример проекта, который вы можете посмотреть, чтобы сделать это.Образец "Рецепты" на сайте разработчика Apple.Вот часть кода, которая может вас заинтересовать:

- (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";
    }

Это всего лишь часть проекта, которая показывает, как создавать различные идентификаторы.Отсюда вы можете получить все сами ...

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