gpt4 book ai didi

ios - 重新排序 UIImage 数组中的元素

转载 作者:行者123 更新时间:2023-11-28 12:50:09 26 4
gpt4 key购买 nike

我有一个 NSURL 数组,我可以使用函数 removeAtIndexinsert。我知道 fromIndexPathtoIndexPath 并且此方法帮助我使用此委托(delegate)方法为 [[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)
}

我的问题是如何在moveDataItem() 中使用newImages 数组,以及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
}()

最佳答案

这应该适用于重新排列任何二维数组:

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
}

关于ios - 重新排序 UIImage 数组中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36757509/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com