iphone, UITextField в UITableView

#xcode #uitableview #uitextfield

#xcode #uitableview #uitextfield

Вопрос:

Я пытаюсь добавить текстовые поля в tableview. Мне нужна метка и текстовое поле в каждой строке, кроме последней. Я хочу переключатель в последней строке. Проблема в том, что текстовые поля накладываются на остальные строки. Я переместил свой код текстового поля внутрь if (cell == nil), но это не сработало … вот мой код

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *MyIdentifier = @"mainMenuIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier] autorelease];
    [cell setSelectedBackgroundView:[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"highlightstrip.png"]]];


    if (tableView.tag == 1) {

        UILabel *lblName = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 90, 20)];
        lblName.textAlignment = UITextAlignmentLeft;
        lblName.font = [UIFont boldSystemFontOfSize:14];
        lblName.backgroundColor = [UIColor clearColor];
        lblName.tag = 31;
        [cell.contentView addSubview:lblName];
        [lblName release];

    }

}

    if (tableView.tag == 1) {

        [(UILabel *) [cell viewWithTag:31] setText:[tableElements objectAtIndex:indexPath.row]];
// check if the last row
        if (indexPath.row == 10) {
            newsSwtich = [[[UISwitch alloc] initWithFrame:CGRectZero] autorelease];
            [newsSwtich addTarget:self action:@selector(switchToggled:) forControlEvents: UIControlEventTouchUpInside];
            cell.accessoryView = newsSwtich;
        }
        else {

                UITextField *tempTextField = [[UITextField alloc] initWithFrame:CGRectMake(100, 10, 200, 20)];
                tempTextField.delegate = self;
                //  tempTextField.placeholder = [tableElements objectAtIndex:indexPath.row];
                tempTextField.font = [UIFont fontWithName:@"Arial" size:14];
                tempTextField.textAlignment = UITextAlignmentLeft;
                tempTextField.tag = indexPath.row;
                tempTextField.autocorrectionType = UITextAutocorrectionTypeNo;  // no auto correction support
                tempTextField.keyboardType = UIKeyboardTypeDefault;  // type of the keyboard
                tempTextField.returnKeyType = UIReturnKeyDone;  // type of the return key
                tempTextField.clearButtonMode = UITextFieldViewModeWhileEditing;    // has a clear 'x' button to the right
                [cell.contentView addSubview:tempTextField];
                [tempTextField release];


            cell.accessoryView = UITableViewCellAccessoryNone;
        }


cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;

}
  

При прокрутке вверх и вниз текстовые поля перекрываются, я имею в виду, что после ввода текста в первой строке и прокрутки вниз я вижу, что текстовое поле скопировано и в последней строке.

Ответ №1:

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

Комментарии:

1. При создании текстового поля / переключателя присвойте ему тег. Скажем, 45. Затем извлеките его с помощью UIView *theView = [cell viewWithTag:45]; . Поскольку теперь у вас есть представление, просто сделайте [theView removeFromSuperview]; . В качестве альтернативы, если это текстовое поле и вам нужно вставить текстовое поле, вы можете сбросить его настройки на те, которые вы хотите. Таким образом, вы можете устранить необходимость его повторного создания.

Ответ №2:

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

 -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {                          
if(indexPath.row==[tableviewarray count]){
//dont add label or textfield
}
else{
// add label or textfield
}

}