我有一个NSURL数组数组,我可以使用函数removeAtIndex
和insert
。我知道fromIndexPath
和toIndexPath
这个方法可以帮助我使用此委托方法[[NSURL]]完成相同的操作(请查看下面的var data
):
func moveDataItem(fromIndexPath : NSIndexPath, toIndexPath: NSIndexPath) {
let name = self.data[fromIndexPath.section][fromIndexPath.item]
self.data[fromIndexPath.section].removeAtIndex(fromIndexPath.item)
self.data[toIndexPath.section].insert(name, atIndex: toIndexPath.item)
// do same for UIImage array
}
但是,我有一个UIImage数组,其中有3个空元素在运行。
var newImages = [UIImage?]()
viewDidLoad() {
newImages.append(nil)
newImages.append(nil)
newImages.append(nil)
}
我的问题我如何使用newImages
内的moveDataItem()
数组以及data
并能够运行这些行以重新排列订购UIImage数组。
我尝试了这些,但不幸的是我无法让它们发挥作用..
self.newImages[fromIndexPath.section].removeAtIndex(fromIndexPath.item)
// and
self.newImages[fromIndexPath.row].removeAtIndex(fromIndexPath.item)
为了澄清,数据数组看起来像这样
lazy var data : [[NSURL]] = {
var array = [[NSURL]]()
let images = self.imageURLsArray
if array.count == 0 {
var index = 0
var section = 0
for image in images {
if array.count <= section {
array.append([NSURL]())
}
array[section].append(image)
index += 1
}
}
return array
}()
答案 0 :(得分:2)
这适用于重新排列任何2d数组:
func move<T>(fromIndexPath : NSIndexPath, toIndexPath: NSIndexPath, items:[[T]]) -> [[T]] {
var newData = items
if newData.count > 1 {
let thing = newData[fromIndexPath.section][fromIndexPath.item]
newData[fromIndexPath.section].removeAtIndex(fromIndexPath.item)
newData[toIndexPath.section].insert(thing, atIndex: toIndexPath.item)
}
return newData
}
示例用法:
var things = [["hi", "there"], ["guys", "gals"]]
// "[["hi", "there"], ["guys", "gals"]]\n"
print(things)
things = move(NSIndexPath(forRow: 0, inSection: 0), toIndexPath: NSIndexPath(forRow:1, inSection: 0), items: things)
// "[["there", "hi"], ["guys", "gals"]]\n"
print(things)
这将适用于普通数组:
func move<T>(fromIndex : Int, toIndex: Int, items:[T]) -> [T] {
var newData = items
if newData.count > 1 {
let thing = newData[fromIndex]
newData.removeAtIndex(fromIndex)
newData.insert(thing, atIndex: toIndex)
}
return newData
}