行と呼ばれる文字列の NSMutableArray を使用する簡単な例として、tableView 行を移動し、変更を配列に反映するには、テーブル コントローラーに何を実装する必要がありますか?
5 に答える
ここで重い物を持ち上げます。
- (void)tableView:(UITableView *)tableView
moveRowAtIndexPath:(NSIndexPath *)fromIndexPath
toIndexPath:(NSIndexPath *)toIndexPath
{
NSLog(@"move from:%d to:%d", fromIndexPath.row, toIndexPath.row);
// fetch the object at the row being moved
NSString *r = [rows objectAtIndex:fromIndexPath.row];
// remove the original from the data structure
[rows removeObjectAtIndex:fromIndexPath.row];
// insert the object at the target row
[rows insertObject:r atIndex:toIndexPath.row];
NSLog(@"result of move :\n%@", [self rows]);
}
これは基本的な例なので、すべての行を移動可能にしましょう。
- (BOOL)tableView:(UITableView *)tableView
canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
return YES;
}
上記のいずれも機能しません。元の投稿されたコードでは、まだ使用されているデータが削除されるため、テーブルビューがクラッシュし、それが修正された後でも、テーブルが「再配置」を行う方法が原因で、配列に正しいデータが含まれません。
exchangeObjectAtIndex:withObjectAtIndex: は、テーブルビューが独自の再配置を実装する方法に従って配列を再配置するために機能しません
なんで?ユーザーが表のセルを選択して再配置する場合、そのセルは移動先のセルと交換されないためです。選択したセルが新しい行インデックスに挿入され、元のセルが削除されます。少なくとも、それがユーザーに表示される方法です。
解決策: テーブルビューが再配置を実装する方法により、正しい行を追加および削除することを確認するためにチェックを実行する必要があります。私がまとめたこのコードはシンプルで、私にとって完璧に機能します。
例として、投稿された元のコード データを使用します。
- (void)tableView:(UITableView *)tableView
moveRowAtIndexPath:(NSIndexPath *)fromIndexPath
toIndexPath:(NSIndexPath *)toIndexPath
{
NSLog(@"move from:%d to:%d", fromIndexPath.row, toIndexPath.row);
// fetch the object at the row being moved
NSString *r = [rows objectAtIndex:fromIndexPath.row];
// checks to make sure we add and remove the right rows
if (fromIndexPath.row > toIndexPath.row) {
// insert the object at the target row
[rows insertObject:r atIndex:toIndexPath.row];
// remove the original from the data structure
[rows removeObjectAtIndex:(fromIndexPath.row + 1)];
}
else if (fromIndexPath.row < toIndexPath.row) {
// insert the object at the target row
[rows insertObject:r atIndex:(toIndexPath.row + 1)];
// remove the original from the data structure
[rows removeObjectAtIndex:(fromIndexPath.row)];
}
}
少し時間を取って、再配置中にテーブルビューに何が起こるかを見てみると、なぜ私たちが行った場所に 1 を追加したのか理解できるでしょう。
私はxcodeを初めて使用するので、おそらくこれを行う簡単な方法があるか、コードを単純化できる可能性があることを知っています....これを理解するのに数時間かかったので、できるところを手伝おうとしていますアウト。これが誰かの時間を節約することを願っています!
Apple のドキュメントと私自身の経験によると、これは非常にうまく機能する単純なコードです。
NSObject *tempObj = [[self.rows objectAtIndex:fromIndexPath.row] retain];
[self.rows removeObjectAtIndex:fromIndexPath.row];
[self.rows insertObject:tempObj atIndex:toIndexPath.row];
[tempObj release];
NSMutableArray
と呼ばれるメソッドがありexchangeObjectAtIndex:withObjectAtIndex:
ます。
単純な実装に頭を悩ませた後、この議論を見つけました... Michael Berdingソリューションは、Appleのやり方で私にとって最高です。ARCを使用するときは保持と解放を削除することを忘れないでください。したがって、より簡潔な解決策
NSObject *tempObj = [self.rows objectAtIndex:fromIndexPath.row];
[self.rows removeObjectAtIndex:fromIndexPath.row];
[self.rows insertObject:tempObj atIndex:toIndexPath.row];