gpt4 book ai didi

ios - 在 tableView 中为不同的 Realm 对象交换和重新加载数据

转载 作者:行者123 更新时间:2023-11-30 11:30:06 24 4
gpt4 key购买 nike

问题 我希望允许用户在表格单元格中点击“交换”,然后找到不同的 Realm 对象来填充单元格中的 2 个文本标签(用于练习名称和重复次数)使用新对象的值。

研究 关于“移动行”(例如这里 How to swap two custom cells with one another in tableview? )和这里( UITableView swap cells )有很多(诚然是旧的),然后显然有很多关于重新加载数据本身的内容但我在这个用例上找不到任何内容。

我尝试了什么我下面的代码可以很好地检索新对象。即单元格中有一些数据,然后当您点击“交换按钮”时,它会抓取另一数据准备放入 tableView 中。我知道如何一般地重新加载数据,但不知道如何在原位的一个特定单元格内重新加载数据(特定交换按钮所属的单元格......每个单元格都有一个“交换按钮”)。

我猜我需要以某种方式找到“swapButton”的indexRow,然后访问该特定单元格的单元格属性,但不确定从哪里开始(我已经尝试过很多不同的变体,但我'我只是猜测,所以它不起作用!)

class WorkoutCell : UITableViewCell {

@IBOutlet weak var exerciseName: UILabel!
@IBOutlet weak var repsNumber: UILabel!
@IBAction func swapButtonPressed(_ sender: Any) {
swapExercise()
}

func swapExercise() {

let realmExercisePool = realm.objects(ExerciseGeneratorObject.self)
func generateExercise() -> WorkoutExercise {
let index = Int(arc4random_uniform(UInt32(realmExercisePool.count)))
return realmExercisePool[index].generateExercise()
}

}
//do something here like cell.workoutName
//= swapExercise[indexRow].generateExercise().name???
}

最佳答案

将对象放置在显示 UITableView 的 VC 中的某个位置。然后将 VC 添加为交换按钮的目标。在按下按钮时实现交换对象,并在之后重新加载 TableView 的数据。整个想法是将逻辑移动到 View Controller ,而不是单独的单元格中。

有两种方法。1. 添加VS作为按钮 Action 目标。

public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = ... // get cell and configure it
cell.swapBtn.addTarget(self, action: #selector(swapTapped(_:)), for: .touchUpInside)
return cell
}

func swapTapped(_ button: UIButton) {
let buttonPosition = button.convertPoint(CGPointZero, toView: self.tableView)
let indexPath = self.tableView.indexPathForRowAtPoint(buttonPosition)!
// find object at that index path
// swap it with another
self.tableView.reloadData()
}
  • 使 VC 成为单元的代表。更多代码。在这里,您在单元格中创建协议(protocol)并添加委托(delegate)变量。然后,当您创建单元格时,您将分配给 VC 作为单元格的委托(delegate):

    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = ...//获取 cell 并配置它 cell.delegate = self 返回单元格 }

    func swapTappedForCell(_ cell: SwapCell) { //交换的逻辑相同}

  • 关于ios - 在 tableView 中为不同的 Realm 对象交换和重新加载数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50339898/

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