Подтвердить что ты не робот

Редактирование ячейки UITableView на месте

Может кто-нибудь, пожалуйста, покажет мне пример локального редактирования ячейки UITableView... Я знаю о методах делегатов UITableView, таких как cellForRowAtIndexPath,... и т.д.

Но я не знаю, как разрешить текстовое редактирование ячейки на месте?
Также это значение может использоваться с основными данными, то есть может ли оно сохраняться.

То, что я ищу, можно увидеть в разделе Настройки → Wi-fi, где вы видите эти поля Домен, Клиент, IP и т.д., где значения могут быть установлены в одном и том же месте.

Также есть ли недостатки в использовании редактирования на месте Vs с отдельным контроллером представления для управления значением поля?

4b9b3361

Ответ 1

Добавить UITextField в свою ячейку.

В любом случае вы можете редактировать запись, независимо от того, используете ли вы CoreData или что-то еще, чтобы сохранить информацию, вам нужно каким-то образом ее сохранить. Если вы перейдете к методу редактирования на основе таблицы, вы можете использовать делегатов textField для сохранения данных по мере возврата пользователей.

В вашем cellForRowAtIndexPath:

myTextField = [[UITextField alloc] initWithFrame:CGRectMake(0,10,125,25)];
myTextField.adjustsFontSizeToFitWidth = NO;
myTextField.backgroundColor = [UIColor clearColor];
myTextField.autocorrectionType = UITextAutocorrectionTypeNo;
myTextField.autocapitalizationType = UITextAutocapitalizationTypeWords;
myTextField.textAlignment = UITextAlignmentRight;
myTextField.keyboardType = UIKeyboardTypeDefault;
myTextField.returnKeyType = UIReturnKeyDone;
myTextField.clearButtonMode = UITextFieldViewModeNever;
myTextField.delegate = self;
cell.accessoryView = myTextField;

TextField Delegates:

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if(textField == myTextField){
        /*  do your saving here  */ 
    }
}

Ответ 2

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

Я создал контроллер представления таблиц, который добавляет окно сообщения, добавляя конец "списка элементов", который хранится в NSUserDefaults... Item

    //
    //  MyItemListTVC.m
    //  Best10
    //
    //  Created by Francois Chaubard on 12/26/13.
    //  Copyright (c) 2013 Chaubard. All rights reserved.
    //

    #import "MyItemListTVC.h"
    #import "AppDelegate.h"

    @interface MyItemListTVC ()

    @property (strong, nonatomic) UIRefreshControl IBOutlet     *refreshControl;
    @property (strong,nonatomic) UIBarButtonItem *addButton;
    @property (strong,nonatomic) UITextView *messageBox;

    @end

    @implementation MyItemListTVC


    @synthesize refreshControl;
    @synthesize itemList;

    - (id)initWithStyle:(UITableViewStyle)style
    {
        self = [super initWithStyle:style];
        if (self) {
            // Custom initialization
        }
        return self;
    }

    - (void)viewDidLoad
    {
        [super viewDidLoad];
        self.itemList=[(AppDelegate *)[UIApplication sharedApplication].delegate getitems];

        // Uncomment the following line to preserve selection between presentations.
        // self.clearsSelectionOnViewWillAppear = NO;

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem;
        // Do any additional setup after loading the view, typically from a nib.
        self.navigationItem.leftBarButtonItem = self.editButtonItem;

        self.addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(insertNewObject:)];

        self.addButton.enabled = false;

        //UIBarButtonItem *saveButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSave target:self action:@selector(save:)];
        [self.navigationItem setRightBarButtonItems:@[self.addButton] animated:YES];
    }



    - (void)didReceiveMemoryWarning
    {
        [super didReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
    }

    - (void)insertNewObject:(id)__unused sender
    {

        NSMutableArray *temp = [[NSMutableArray alloc] initWithArray:self.itemList];

        self.itemList = nil;
        [self.tableView reloadData];

        [temp addObject:self.messageBox.text];
        [[NSUserDefaults standardUserDefaults] setObject:temp  forKey:@"items"];
        self.itemList=[(AppDelegate *)[UIApplication sharedApplication].delegate getitems];
        self.messageBox = nil;
        self.addButton.enabled = NO;
        [self.tableView reloadData];

        [self.tableView setNeedsDisplay];
        [CATransaction flush];
    }

    - (void) save:(id)__unused sender {


    }



    #pragma mark - Table View


    - (NSInteger)tableView:(UITableView *)__unused tableView numberOfRowsInSection:(NSInteger)section
    {

        return [self.itemList count]+1;
    }

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        UITableViewCell *cell;
        if (indexPath.row ==[self.itemList count]  ) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MessageBox Cell"];

            UITextView *messageBox= [[UITextView alloc] initWithFrame:CGRectMake(0, 0, cell.frame.size.width, 100)];

            cell.userInteractionEnabled=YES;
            messageBox.delegate=self;
            [messageBox setEditable:YES];
            [messageBox setUserInteractionEnabled:YES];
            messageBox.editable=YES;
            messageBox.font = cell.textLabel.font;
            messageBox.textAlignment = NSTextAlignmentCenter;
            messageBox.textColor = [UIColor grayColor];
            messageBox.text = @"insert new activity";
            self.messageBox = messageBox;
            [cell addSubview: messageBox];
        }else{
            cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];

            [self configureCell:cell atIndexPath:indexPath];
        }
        return cell;
    }

    - (BOOL)tableView:(UITableView *)__unused tableView canEditRowAtIndexPath:(NSIndexPath *)__unused indexPath
    {
        // Return NO if you do not want the specified item to be editable.
        return YES;
    }

    - (void)tableView:(UITableView *)__unused tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
    {
        if ((editingStyle == UITableViewCellEditingStyleDelete)&&([self.itemList count]>indexPath.row)) {

            NSMutableArray *temp = [[NSMutableArray alloc] initWithArray:self.itemList];
            [temp removeObjectAtIndex:indexPath.row];
            [[NSUserDefaults standardUserDefaults] setObject:temp  forKey:@"items"];
            self.itemList=[(AppDelegate *)[UIApplication sharedApplication].delegate getitems];
            [self resignFirstResponder];

            [self.tableView reloadData];
        }
    }

    - (BOOL)tableView:(UITableView *)__unused tableView canMoveRowAtIndexPath:(NSIndexPath *)__unused indexPath
    {
        // The table view should not be re-orderable.
        return YES;
    }




    - (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
    {
        if ([self.itemList count] > 0){

            cell.textLabel.text = [self.itemList objectAtIndex:indexPath.row];

        }
    }

    #pragma mark - UITextViewDelegate
    - (void)textViewDidBeginEditing:(UITextView *)textView {

        textView.text = @"-ing";
        [self.messageBox setSelectedTextRange:[self.messageBox textRangeFromPosition:[self.messageBox positionFromPosition:self.messageBox.beginningOfDocument offset:1] toPosition:self.messageBox.beginningOfDocument]];


    }
    -(void)textViewDidChange:(UITextView *)textView
    {
        if (textView.text.length > 4) {
            self.addButton.enabled=YES;
        }else{
            self.addButton.enabled=NO;
        }
    }

    - (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        if ((indexPath.row ==[self.itemList count] ) ) {
            return UITableViewCellEditingStyleNone;
        }else{
            return UITableViewCellEditingStyleDelete;
        }
    }

    - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
        if ([text isEqualToString:@"\n"]) {

            if (textView.text.length > 4) {
                [self insertNewObject:textView.text];
            }
            [self resignFirstResponder];
            return NO; // or true, whetever you like

        }else if((textView.text.length-range.location)<4){
            return NO;
        }

        if (textView.text.length > 4) {
            self.addButton.enabled=YES;
        }else{
             self.addButton.enabled=NO;
        }
        return YES;
    }

    @end