我试图理解可拖动 Collection View 单元格的逻辑。它适用于虚拟数据,但是我无法弄清楚如何使其适用于真实数据。
我不知道给这个问题起什么标题,请随时编辑/改进它
如果我将这种方法与虚拟数组项一起使用并调用该函数
class TableViewController: UITableViewController, KDRearrangeableCollectionViewDelegate, UICollectionViewDataSource {
lazy var data : [[String]] = {
var array = [[String]]()
let images = [
"1.jpg", "2.jpg", "3.jpg"
]
if array.count == 0 {
var index = 0
var section = 0
for image in images {
if array.count <= section {
array.append([String]())
}
array[section].append(image)
index += 1
}
}
return array
}()
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)
print(self.data)
}
此时 print(self.data)
打印拖动/重新排列后数组项的新顺序。
示例 print(self.data
) 日志:
[["2.jpg", "1.jpg", "3.jpg"]]
现在我有了真实的数据,并且在从数据库中获取数据后,它会被附加到项目中。
var realImages = [NSURL]()
// I tried assigning `images` array inside `lazy var data` but received error:
lazy var data : [[String]] = {
var array = [[String]]()
let images = realImages // error here
...
Instance member realImages cannot be used on type TableViewController
在这种情况下,使用真实数组的正确方法是什么?
(This explanation 和 its Git repo 非常适合理解它)。我使用虚拟数据进一步简化了它,但我无法理解“惰性变量”和常规“变量”的逻辑以及如何使其在这种情况下工作
最佳答案
您需要像 let images = self.realImages
一样显式使用 self。
lazy var data : [[String]] = { [unonwed self] in
var array = [[String]]()
let images = self.realImages // error gone :)
(请注意,我们必须在这里说 [unowned self] 以防止 strong reference cycle )
关于ios - 将 'class variable' 分配给 'lazy var' 内的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36713445/