[英]IOS: How to convert NSArray to NSIndexPath
我想批量插入UITableview。
MyArray.all() do |datas|
self.tableView.beginUpdates
self.tableView.insertRowsAtIndexPaths(datas, withRowAnimation: UITableViewRowAnimationFade)
self.tableView.endUpdates
self.myarrayvar += datas
end
“ myarrayvar”是MyArray的數組。 我試圖參考Apple文檔
和stackoverflow這類似於我的問題。
但是我真的不知道如何轉換我的數據以適合insertRowsAtIndexPaths函數的參數。
使用rubymotion
這是我目前使用的一種方式:
def insertCellsAtBottom(newData)
# Get count for the existing data you have.
currentCount = @data.count
# Build the indexPaths for the new data, adding to the current count each time.
# This will make sure you are creating the correct indexes.
indexPaths = newData.map.with_index do |obj, index|
NSIndexPath.indexPathForRow(currentCount + index, inSection: 0)
end
# Update your datasource and insert the rows.
self.tableView.beginUpdates
@data.addObjectsFromArray(newData)
self.tableView.insertRowsAtIndexPaths(indexPaths, withRowAnimation: UITableViewRowAnimationFade)
self.tableView.endUpdates
end
您的MyArray
包含對象數組。 insertRowsAtIndexPaths:withRowAnimation
方法用於告知tableView您已向數據源中添加了項目,並且應該去該項目並在您提供的indexPath處請求該數據。
您采取的步驟是:
因此,例如,如果您以數組開頭並添加一個對象,則需要執行此操作
# Start with empty data model
my_array = []
# Update the model to have one object
my_array << my_new_object
# Tell the table that you have updated your model by inserting one object at the beginning of the first section
inserted_index_paths = [ NSIndexPath.indexPathForRow(0, inSection: 0]) ]
self.tableView.insertRowsAtIndexPaths(inserted_index_paths, withRowAnimation: UITableViewRowAnimationFade)
如果您隨后再次在末尾插入一個對象,則看起來非常相似,只是新插入的索引路徑為NSIndexPath.indexPathForRow(1, inSection: 0)
因為您現在告訴tableView您已將第二個對象插入到第一部分
你應該做類似的事情
index_paths = MyArray.map { |index| NSIndexPath.indexPathForRow(index, inSection: 0) }
self.tableView.beginUpdates
self.tableView.insertRowsAtIndexPaths(index_paths, withRowAnimation: UITableViewRowAnimationFade)
self.tableView.endUpdates
在obj-c中,這是這樣做的方法...如果您從NSMutableArray獲取數據,則只需在其中進行操作即可。
例如,我得到了
array = @[@"text1", @"text2", @"text4"];
對於我的單元格,我正在調用cellForRowAtIndexPath方法:
[cell setText:array[indexPath.row]];
在我的陣列中,我正在:
array[2] = @"text3";
接着 :
[self.tableView reloadData];
我沒有對此進行測試,但這是插入新行的好方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.