gpt4 book ai didi

ios - 动态/可取消排队的 UITableviewcells 中的 UITextfield

转载 作者:行者123 更新时间:2023-11-29 12:32:49 24 4
gpt4 key购买 nike

我的这个表格 View 有足够多的单元格需要滚动,每个单元格都是一个包含标签和 UITextField 的自定义单元格。我正在尝试 this解决方案

当我在文本字段中输入文本并滚动表格 View 以查看其他单元格时,我之前写的文本消失了,留下一个空白的文本字段。

This这是我遇到的问题

我的 cellForRowAtIndexPath 代码是:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *CellIdentifier = @"Mycell";
MyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil) {
cell = [[MyTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}


// Configure the cell...

cell.myLabel.text = [labelarray objectAtIndex:indexPath.row];
cell.myTextbox.tag = indexPath.row;
cell.myTextbox.text = stringVariable;



return cell;
}

stringVariable 在.h 中声明

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

NSMutableArray *labelarray ;
NSString *stringVariable;
__weak IBOutlet UITableView *myTableview;
}

我在这里初始化了它:

-(void)textFieldDidEndEditing:(UITextField *)textField{
MyTableViewCell *cell;
stringVariable = [[NSString alloc]init];
if (textField == cell.myTextbox) {
self->stringVariable = cell.myTextbox.text;
}
}

最佳答案

问题是,当单元格离开屏幕时,它们会被销毁,当它们再次出现时会被重新创建。

要保留输入的数据,您需要使用 UITextField 委托(delegate)方法 textFieldDidEndEditing: 来存储它。

你在那个方法中所做的是错误的。首先,你不是你的单元格对象没有指向任何地方,它总是 nil。其次,您不能用一个变量 (stringVariable) 来存储所有数据,您需要一个数组,这样每个元素将对应一个文本字段。

添加属性:

@property (strong, nonatomic) NSMutableArray *textFieldData;

然后分配它:

- (void)viewDidLoad {
// ...
self.textFieldData = [[NSMutableArray alloc] initWithCapacity:<number of rows>];
// ...
}

然后代表:

- (void)textFieldDidEndEditing:(UITextField *)textField{
self.textFieldData[[textField tag]] = textField.text;
}

对于您拥有的每个 UITextField,不要忘记将您的 Controller 设置为委托(delegate)。

最后,当您重新创建单元格时,使用:

cell.myTextbox = self.textFieldData[indexPath.row];

关于ios - 动态/可取消排队的 UITableviewcells 中的 UITextfield,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27178758/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com