Я думаю, что лучше получать данные из массива 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