gpt4 book ai didi

arrays - 如何在 iOS Swift 的 didselect 方法中重新排列单元格?

转载 作者:行者123 更新时间:2023-11-28 13:27:58 24 4
gpt4 key购买 nike

假设我有一个数组 ["one","two","three","four","five"]。我想用 didselect 方法重新排列单元格。

例如:

var items = [UserObject]()

型号:

 import SwiftyJSON

class UserObject {

var URL: String!
var Name: String!


required init(json: JSON) {
URL = json["URL"].stringValue
Name = json["Name"].stringValue
}
}

当点击单元格二时,数组应该是 ["two","three","four","five","one"]

当点击单元格四时,数组应该是 ["three","four","five","one","two"]

我这样试过,效果很好,但我需要另一种方法

在didselect方法中

var data = self.items[0]
self.items.remove(at: 0)
self.items.insert(data, at: 4)
tableView.reloadData()

有没有其他方法可以实现这一点?

我如何使用 tableview 和不使用 tableview 来实现这一点?

最佳答案

当您点击一个cell/index 时,您会将所选单元移动到index 0

您可以实现此扩展,并在需要移动时使用它:

extension Array {
func shiftRight(_ amount: Int = 1) -> [Element] {
var amount = amount
assert(-count...count ~= amount, "Shift amount out of bounds")
if amount < 0 { amount += count } // this needs to be >= 0
return Array(self[amount ..< count] + self[0 ..< amount])
}

mutating func shiftRightInPlace(amount: Int = 1) {
self = shiftRight(amount)
}
}

source

现在,对于您的 UICollectionViewUITableView,您可以在 didSelect 函数中轻松使用它。

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
items = items.shiftRight(indexPath.row)
}

最后一步是向您的数据源添加一个属性监听器,这样您就可以在 tableViewcollectionView 像这样更改值时自动刷新

var items = ["one","two","three","four","five"] {
didSet {
//tableView.reloadData()
}
}

除了你的情况:

改变这个:var items = [UserObject]()

对此:

var items: [UserObject] = [] {
didSet {
DispatchQueue.main.async {
tableView.reloadData()
}
}
}

关于arrays - 如何在 iOS Swift 的 didselect 方法中重新排列单元格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58026330/

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