![](/img/trans.png)
[英]Scrolling tableview causes checkmark to disappear | addressing reusable cells in Swift 5
[英]iOS scrolling tableView reusable cells reload
我正在使用iOS中的表tableviews
。 滾動時會重新加載可重復使用的單元格。
因此,在更新單元格內的textfields
時,例如,滾動時,它會消失。 我通過使用將所有文本保存在所有單元格中的Array
解決了這個問題,但是我想知道是否有更好的方法來解決此問題。
謝謝。
使用字符串數組,您必須在表視圖中存儲所有文本字段的數據。 使用UITableView
委托方法可以更有效地實現。
-(void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
MyCell * mc = (MyCell *) cell;
names[indexPath.row] = mc.myTf.text;
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
MyCell * mc = (MyCell *) cell;
mc.myTf.text = names[indexPath.row];
}
在這里,MyCell是具有UITextField
的自定義單元格。 name []是在類范圍內聲明的NSString
數組,例如NSString * names[20]
。
對於內存管理(釋放內存),tableview刪除當前屏幕上未顯示的單元格內存,它僅將那些當前顯示在屏幕上的單元格保留在內存中,因此您必須將該文本與tableview分開存儲。
您要描述的是表視圖是如何工作的! tableView是顯示而不是存儲,可重用單元格僅是當前顯示的那些單元格
您可以使用數組(或集合)來保存數據,而只需要使用tableView來顯示它
您的問題可能是由於多線程。 如果要從GCD操作或任何NSOperation(不同的線程)重新加載數據,則必須使用以下代碼來獲取主線程的句柄
dispatch_sync(dispatch_get_main_queue(), ^{
//perform the reload activity
});
是的,您做對了,因為單元已被重用,所以您需要保存數據,例如:
1。 有一個數組來保存您的數據。
2。 每當您對textFields進行任何更改時,都要更新數組,以使UI和數據保持同步。
您需要將cellIdentifier定義為唯一。 然后,每個單元格都創建有唯一標識符。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *CellIdentifier = [NSString stringWithFormat:@"Cell%dR%d",indexPath.section,indexPath.row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
//your logic here
}
return cell;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.