Текстовое поле появляется несколько раз UItableViewGrouped - PullRequest
2 голосов
/ 04 июня 2011

Я нашел пример кода для реализации текстового поля в ячейку здесь: Наличие UITextField в UITableViewCell

Однако текстовое поле несколько раз появляется в моей таблице в 1-м разделетаблицы, хотя я указал, что он появляется, только когда он подходит ко 2-му разделу таблицы и к первой строке этого раздела.

Любые объяснения, почему это происходит?Я только хочу это во 2-й секции 1-го ряда.но кажется, что всякий раз, когда появляется 2-й раздел, он просто рисует текстовое поле заранее.Есть ли способ «привязать» его к определенной группе и ячейке?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil) {
    cell = [self CreateMultilinesCell:CellIdentifier];
}
NSLog(@"%d", [indexPath section]);
if ([indexPath section] == 1) {
    NSLog(@"TextField");

    if ([indexPath row] == 0 ) {
        UITextField *replyTextField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 185, 30)];
        replyTextField.adjustsFontSizeToFitWidth = YES;
        replyTextField.textColor = [UIColor blackColor];

        replyTextField.keyboardType = UIKeyboardTypeDefault;
        replyTextField.returnKeyType = UIReturnKeyDone;
        replyTextField.backgroundColor = [UIColor grayColor];
        replyTextField.autocorrectionType = UITextAutocorrectionTypeNo; 
        replyTextField.autocapitalizationType = UITextAutocapitalizationTypeNone;
        replyTextField.textAlignment = UITextAlignmentLeft;
        replyTextField.tag = 0;
        replyTextField.delegate = self;

        replyTextField.clearButtonMode = UITextFieldViewModeNever;
        [replyTextField setEnabled: YES];

        [cell.contentView addSubview:replyTextField];

        [replyTextField release];
        cell.detailTextLabel.text = @"something";

    }
}
else {
    cell.detailTextLabel.text = [separatedString objectAtIndex:indexPath.row];
}

return cell;
}

createmultilinecell:

- (UITableViewCell*) CreateMultilinesCell :(NSString*)cellIdentifier
{
//NSLog(@"Entering CreateMultilinesCell");
UITableViewCell *cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle 
                                                reuseIdentifier:cellIdentifier] autorelease];

cell.detailTextLabel.numberOfLines = 0;
cell.detailTextLabel.font = [self SubFont];
cell.detailTextLabel.textColor = [UIColor colorWithRed:10.0/255 green:10.0/255 blue:33.0/255 alpha:1.0];
[cell setBackgroundColor:[UIColor clearColor]];//]colorWithRed:.98 green:.98 blue:.99 alpha:1.0]];
[self.tableView setBackgroundColor:[UIColor clearColor]];//colorWithRed:.94 green:.96 blue:.99 alpha:1.0]];
                                                         //NSLog(@"Exiting CreateMultilinesCell");
return cell;
}

argh Я слишком низок, чтобы ответить на мой собственный вопрос, поэтому яЯ просто обновлю здесь:

Похоже, заставить работать 2 cellidentifiers.Благодарю.Просто узнал что-то новое!ха-ха.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
NSString *replyCellIdentifier = @"replyCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
UITextField *replyTextField;
if (cell == nil) {
    if ([indexPath section] == 0) {
        cell = [self CreateMultilinesCell:CellIdentifier];      
    }
    else if ([indexPath section] == 1) {
        NSLog(@"TextField");
        cell = [self CreateMultilinesCell:replyCellIdentifier];     
        if ([indexPath row] == 0) {
            replyTextField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 185, 30)];
            replyTextField.adjustsFontSizeToFitWidth = YES;
            replyTextField.textColor = [UIColor blackColor];
            replyTextField.keyboardType = UIKeyboardTypeDefault;
            replyTextField.returnKeyType = UIReturnKeyDone;
            replyTextField.backgroundColor = [UIColor grayColor];
            replyTextField.autocorrectionType = UITextAutocorrectionTypeNo; 
            replyTextField.autocapitalizationType = UITextAutocapitalizationTypeNone;
            replyTextField.textAlignment = UITextAlignmentLeft;
            replyTextField.tag = 0;
            replyTextField.delegate = self;

            replyTextField.clearButtonMode = UITextFieldViewModeNever;
            [replyTextField setEnabled: YES];

            [cell.contentView addSubview:replyTextField];

            [replyTextField release];
            cell.detailTextLabel.text = @"something";
        }           
    }
    /*else {
        cell.detailTextLabel.text = [separatedString objectAtIndex:indexPath.row];
    }*/
}
NSLog(@"%d", [indexPath section]);
if ([indexPath section] == 0) {
    cell.detailTextLabel.text = [separatedString objectAtIndex:indexPath.row];

}
return cell;
}

спасибо всем, кто внес свой вклад.

С точки зрения функциональности я еще не уверен, но это на шаг ближе к тому, чтобы достичь того, чего я хочу :).

Ответы [ 3 ]

3 голосов
/ 04 июня 2011

Попробуйте использовать две разные ячейки, одну с текстовым полем и одну без.Используйте разные строки CellIdentifier для двух разных типов ячеек.Это должно решить это.

0 голосов
/ 04 июня 2011

Попробуйте, если вы используете раздел

NSString *CellIdentifier = [NSString stringWithFormat:@"S%1dR%1d",indexPath.section,indexPath.row]

, а если вы не используете раздел, то используйте

NSString *CellIdentifier = [NSString stringWithFormat:@"Cell%i",indexPath.row];

0 голосов
/ 04 июня 2011

Это потому, что у вас есть эта часть кода вне if(cell == nil)

if ([indexPath row] == 0 ) {
    UITextField *replyTextField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 185, 30)];
    ...........

}

Так что эта строка кода всегда вызывается, когда вы прокручиваете табличное представление, чтобы увидеть эту строку и, таким образом, каждый раз добавлять поле uitext.Итак, что вы можете сделать

Объявите эту переменную в этом блоке if(cell == nil){....}

Также, если вы не добавляете или удаляете какие-либо строки или разделы в своем табличном представлении, это будет работать просто отлично.

* PS. * Обработка табличного представления намного сложнее, когда вы используете его для отображения динамических данных, которые пользователь может редактировать.

Вам придется сделать больше, чемэто, но сейчас я думаю, что вы хорошо, чтобы начать.

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