gpt4 book ai didi

swift - 协议(protocol)在单元中被重置

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

我有一个带有文本字段和按钮的单元格。该按钮打开一个页面来收集数据,并有一个协议(protocol)将该数据传递回单元格并填充文本字段。一切正常,但是,当我回来时,该值重置为零。打印语句显示它在设置时传递数据,但由于某种原因按 Back 会清除它。

协议(protocol)

protocol DistanceProtocol {
func distanceSet(distance: Double)
}

调用协议(protocol)方法

distanceProtocol?.distanceSet(totalDistance)

细胞类别

class InputCell: CalculatorCell, DistanceProtocol {

@IBOutlet var textField: UITextField?

private var inputType = InputType.undefined

var viewController = UIViewController()

override func getHeight() -> CGFloat {
return 90
}

func distanceSet(distance: Double) {
print(distance)
textField?.text = "\(distance)"
}

func getInputType() -> InputType {
return inputType
}

func setInputType(inputType: InputType) {
self.inputType = inputType
}

@IBAction func walkTouched(sender: UIButton) {
let mapVc = viewController.storyboard!.instantiateViewControllerWithIdentifier("Map") as! MapLocationsViewController

mapVc.distanceProtocol = self

viewController.navigationController?.pushViewController(mapVc, animated: true)
}
}

据我所知,一切都设置正确。当我回来时,它不会重新加载 tableView 中的单元格。为什么会重置/如何防止它?

最佳答案

文本字段仅在您调用该函数时设置。除非您在 cellForRowAtIndex 路径中调用此函数,否则它不会保留该值

我可能会使用 setter 来实现它,每次设置值时都会更新标签

protocol DistanceProtocol {
func distanceSet(distance: Double)
}

class CellWithText: UITableViewCell {

var cellText: String {
didSet {
textLabel?.text = cellText
}
}

}

extension CellWithText: DistanceProtocol {
func distanceSet(distance: Double) {
self.cellText = "\(distance)"
}
}

然后在 cellForRowAtIndexPath 调用中您将调用该函数

cell.distanceSet(19.0)

关于swift - 协议(protocol)在单元中被重置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39793420/

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