作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
假设我有一个数组 ["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)
}
}
现在,对于您的 UICollectionView
或 UITableView
,您可以在 didSelect
函数中轻松使用它。
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
items = items.shiftRight(indexPath.row)
}
最后一步是向您的数据源添加一个属性监听器,这样您就可以在 tableView
或 collectionView
像这样更改值时自动刷新
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/
我是一名优秀的程序员,十分优秀!