Сохранить данные табличного представления в массиве по нажатию кнопки - Цель c - PullRequest
0 голосов
/ 24 сентября 2018

У меня есть UITableView с каждой ячейкой, имеющей текстовые поля.Я хочу получить текст, записанный в этом текстовом поле, в NSMutableArray

В настоящее время я делаю это по нажатию кнопки -

- (void)viewDidLoad {
    [super viewDidLoad];
   _optionTextArray = [[NSMutableArray alloc] init];

}

- (IBAction)saveClicked:(UIButton *)sender {

    editVotingOptionCell *cell = [_tableView dequeueReusableCellWithIdentifier:@"cell"];

    for (int i=0; i<_optionArray.count; i++) {
        [_optionTextArray addObject:cell.tfOption.text];
    }
}

Но каждый раз при сохранении пустой строки.

Ответы [ 4 ]

0 голосов
/ 25 сентября 2018

Я думаю, что лучше получать данные из массива dataSource tableView , а не из ячеек.

Так что каждый раз, когда текст textField менялся, вы должны хранить его значение, я написал для вас демонстрацию:

Это MyCell.h код:

#import <UIKit/UIKit.h>

typedef void(^TextFieldValueChangedBlock)(NSString *text);

@interface MyCell : UITableViewCell

@property (nonatomic, copy) TextFieldValueChangedBlock textFieldValueChangedBlock;

@property (nonatomic, copy) NSString *textFieldValue;

@end

Это MyCell.m код:

#import "MyCell.h"

@interface MyCell ()

@property (nonatomic, strong) UITextField *myTextField;

@end

@implementation MyCell 

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        self.myTextField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 200, 40)];
        [self.contentView addSubview:self.myTextField];
        [self.myTextField addTarget:self action:@selector(textFieldChanged:) forControlEvents:UIControlEventEditingChanged];
    }
    return self;
}

- (void)textFieldChanged:(UITextField *)textField {
    if (self.textFieldValueChangedBlock) {
        self.textFieldValueChangedBlock(textField.text);
    }
}

- (void)setTextFieldValue:(NSString *)textFieldValue {
    self.myTextField.text = textFieldValue;
}

@end

Наконец-то это ViewController.m код:

#import "ViewController.h"
#import "MyCell.h"

@interface ViewController () <UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;

@property (nonatomic, strong) NSMutableArray *stringArray;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    self.dataArray = [NSMutableArray array];
    for (int i = 0; i < 100; i++) {
        [self.dataArray addObject:@"text"];
    }

    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:self.tableView];
    self.tableView.dataSource = self;
}

- (void)saveClicked:(UIButton *)sender {
    self.stringArray = self.dataArray.mutableCopy;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellReuseID = @"cell";
    MyCell *cell = [tableView dequeueReusableCellWithIdentifier:cellReuseID];
    if (!cell) {
        cell = [[MyCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellReuseID];
    }
    cell.textFieldValue = self.dataArray[indexPath.row];
    // textField value change,store value
    __weak typeof(self) weakSelf= self;
    cell.textFieldValueChangedBlock = ^(NSString *text) {
        __strong typeof(self) strongSelf = weakSelf;
        [strongSelf.dataArray replaceObjectAtIndex:indexPath.row withObject:text];
    };
    return cell;
}

@end
0 голосов
/ 24 сентября 2018

Вы можете попробовать

(IBAction)saveClicked:(UIButton *)sender {

     for (int i=0; i<_optionArray.count; i++) {

        editVotingOptionCell *cell = [_tableView cellForRowAtIndexPath: [NSIndexPath indexPathForRow:i inSection:0]];
        if (cell != nil) {
          [_optionTextArray addObject:cell.tfOption.text];
        }
        else {
          NSLog(@"nil cell")
        }

    }
}

//

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath { 
   editVotingOptionCell*cell = ///
   cell.tfOption.delegate = self;
   cell.tfOption.tag = indexPath.row;
   return cell;
}
-(void)textFieldDidEndEditing:(UITextField *)textField {
   _optionTextArray[textField.tag] = textField.text 
}

//

@interface ViewController : UIViewController <UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>

Примечание: предварительно инициализировать массив_optionTextArray со значениями по умолчанию

0 голосов
/ 24 сентября 2018

Если все ячейки видны, как вы сказали, вы можете сделать это следующим образом:

- (IBAction)saveClicked:(UIButton *)sender {
    for (int i=0; i < _tableView.visibleCells.count; i++) {
       editVotingOptionCell *cell = self.tableView.visibleCells[i];
       [_optionTextArray addObject: cell.tfOption.text];
    }
}

ОБНОВЛЕНИЕ:

Этот метод можно использовать, только если все вашивидимые ячейки.

Из-за повторного использования вы не можете получить textField в привязке к конкретной ячейке.Таблица просмотра повторно использовать ячейки.

Так что совет, который вы можете увидеть ниже, с cellForRowAtIndexPath: indexPath не очень хорошая идея из-за политики табличного представления.

Если вы хотите получить весь текст из ячеек, вы должны сохранить его в массиве в другом месте, а не в ячейках табличного представления.Например, вы можете сохранить текст из текстового поля в методе UITextFieldDelegate после обновления текстового поля.

0 голосов
/ 24 сентября 2018
@interface MyCell: UITableViewCell {
    @property(strong) UITextField *textField;
}

Предположим, у вас есть ячейка с классом MyCell, когда вы нажимаете кнопку, чтобы получить количество строк в разделе.Пусть у вас есть секция по умолчанию, равная 0, так что получите количество строк для нулевой секции после этой итерации по циклу и получите ячейку в каждом indexPath и получите текст из этого indexPath и проверьте, является ли текст пустым или нет, и, наконец, вставьтеэто в массив.Ниже приведен пример кода нажатия кнопки.

    NSInteger numberOfRows = [self.tableView numberOfRowsInSection:0]
    NSMutableArray *allTexts = [NSMutableArray new];
    for (NSInteger i = 0; i< numberOfRows; i++) {
         NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
         MyCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
        if (cell.textField.text != nil) {
            [allText addObject:cell.textField.text];
        }

}
...