[英]Table view scrolling the text filed value not persist
我在表格視圖單元格上有一個UITableView
一些UITextField
。 UITextField
用戶在文本字段中輸入一些值,然后滾動表格視圖。文本字段上的值不會保留。 下面的代碼
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 100;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
static NSString *CellIdentifierFirst = @"CellFirst";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifierFirst];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:CellIdentifier] autorelease];
}
NSArray *cellSubs = cell.contentView.subviews;
for (int i = 0 ; i < [cellSubs count] ; i++) {
[[cellSubs objectAtIndex:i] removeFromSuperview];
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
UITextField * textFieldRounded = [[UITextField alloc] initWithFrame:CGRectMake(100, 5, 150, 40)];
textFieldRounded.borderStyle = UITextBorderStyleNone;
textFieldRounded.textColor = [UIColor blackColor];
textFieldRounded.font = [UIFont systemFontOfSize:17.0];
textFieldRounded.placeholder = @"Type here";
textFieldRounded.backgroundColor = [UIColor whiteColor];
textFieldRounded.autocorrectionType = UITextAutocorrectionTypeNo;
textFieldRounded.keyboardType = UIKeyboardTypeDefault;
textFieldRounded.returnKeyType = UIReturnKeyDone;
textFieldRounded.clearButtonMode = UITextFieldViewModeWhileEditing;
textFieldRounded.delegate = self;
[cell.contentView addSubview:textFieldRounded];
return cell;
}
所以請大家幫幫我
我在我的一個應用程序中具有相同的功能,我使用下面的代碼來實現這一點,我從來沒有遇到過這種問題。
首先,您需要將所有 textField 值臨時存儲在 Array 中。 像這樣制作數組。
arrTemp=[[NSMutableArray alloc]initWithObjects:[NSString stringWithFormat:@""],
[NSString stringWithFormat:@""],
[NSString stringWithFormat:@""],
[NSString stringWithFormat:@""],
[NSString stringWithFormat:@""],
[NSString stringWithFormat:@""],
[NSString stringWithFormat:@""],
[NSString stringWithFormat:@""],
[NSString stringWithFormat:@""],nil];
然后給所有 textField tag = indexPath.row;
之后,您需要在以下兩種方法中替換 textField 值。
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
[arrTemp replaceObjectAtIndex:textField.tag withObject:textField.text];
}
-(void)textFieldDidEndEditing:(UITextField *)textField{
[arrTemp replaceObjectAtIndex:textField.tag withObject:textField.text];
}
最后,您需要在 cellForRowAtIndexPath 數據源方法中設置該值。 因此,每當用戶滾動 tableview 時,它都會從臨時數組中設置先前的值。 像這樣。
cell.txtEntry.text = [arrTemp objectAtIndex:indexPath.row];
我可能忘記了一些要粘貼在這里的代碼。 因此,如果您有任何問題,請告訴我。
您將需要為所有行維護一個可變數組。 每次更改文本時,您都必須將文本存儲在該數組中,並在調用cellForRowAtIndexPath:
時從數組中設置文本。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.