在swift中更新标签中的滑块值
我有一个带标签的滑块视图。我需要在滑块移动时更新标签值。滑块正在工作,我能够在日志中获取滑块值。但标签值仅在重新加载表视图或相应单元格后更新。这会导致闪烁影响在swift中更新标签中的滑块值,swift,Swift,我有一个带标签的滑块视图。我需要在滑块移动时更新标签值。滑块正在工作,我能够在日志中获取滑块值。但标签值仅在重新加载表视图或相应单元格后更新。这会导致闪烁影响 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { { rangeSlider.backgroundColor = UIColor.clear cell.addSubview(
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
{
rangeSlider.backgroundColor = UIColor.clear
cell.addSubview(rangeSlider)
rangeSlider.tag = indexPath.row
rangeSlider.addTarget(self, action: #selector(PresentedViewController.rangeSliderValueChanged), for: .valueChanged)
NotificationCenter.default.addObserver(self, selector: #selector(showSliderValue), name: NSNotification.Name(rawValue: "slidervalue"), object: nil)
{
cell.currentMaximumValue.text = self.upperSliderText
cell.currentMinimumValue.text = self.LowerSliderText
}
else{
let b:String = String(format:"%f", appDelegate.priceslidermaximumValue)
let c:String = String(format:"%f", appDelegate.pricesliderminimumValue)
cell.currentMaximumValue.text = b
cell.currentMinimumValue.text = c
}
return cell
}
您需要在代码中更改几件事 首先,在
cellForRowAt
方法中,如果通过dequeueReusableCell
获取单元格对象,则在执行addSubview
操作时需要小心。因此,您的单元对象只是一个可重用的单元,可能已经有了一个滑块。如果在添加子视图之前未清理所有视图,则在上下滚动一段时间后,单元格中将充满滑块,可能会崩溃。我建议您在序列图像板的自定义表格视图单元格中添加此滑块
其次,不要使用NotificationCenter.default.addObserver
。由于为每个准备显示的单元格调用了cellForRow
,因此您需要多次添加观察者
那么答案就在这里
创建一个数组来存储每个单元格的滑块值
var sliderValues = [10, 20, 30, 40]
在您的cellForRow
中,只需添加如下侦听器
cell.textField.text = sliderValues[indexPath.row]
cell.slider.tag = indexPath.row // Use tag to see which cell your slider is located
cell.slider.addTarget(self, action: #selector(sliderValueChanged), for: UIControlEvents.valueChanged)
然后在您的函数中与侦听器一起工作
func sliderValueChanged(sender: UISlider){
sliderValues[sender.tag] = sender.value
self.tableView.reloadData()
}
谢谢你的回复。
为了解决重新加载单元时的闪烁效应,我使用了以下行
tableView.reloadSections(IndexSet(integer: indexPath.section),
with: UITableViewRowAnimation.fade)
这对我很有用。你在TableView单元格中有滑块吗?是的,在table view单元格中显示
cellForRowAt的代码
这会让我们知道你是如何在TableView中填充数据的。我不知道在哪里包含更新标签的代码……它是在table view单元格中还是在CELLforRow的索引路径委托中?你需要使用带有tableView的dat源数组,用于维护每个单元格的滑块当前值