首页 > 解决方案 > 单击按钮时将表视图数据存储在数组中 - 目标 c

问题描述

我有一个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];
    }
}

但是每次都存储空字符串。

标签: iosobjective-carraysuitableviewloops

解决方案


@interface MyCell: UITableViewCell {
    @property(strong) UITextField *textField;
}

假设您有一个带有类的单元格,MyCell当您的按钮被点击时,首先获取部分中的行数。让你有一个默认部分,0这样在循环遍历后获取第 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];
        }

}

推荐阅读