Reputation: 993
I have one UISlider and one UILabel. I want to reflect the value from that UISlider to my UILabel. I have a UITableViewCell where I have both outlets and I have a ViewController where I connected the Slider and I create an action function (ValueChanged). I did the logic in that function but is not working because is saying that my outlet is NIL. Can anyone help me to pass this data correctly ? Maybe can be done with Delegates but I don't know how more exactly.
Here is my code for UITableViewCell:
import UIKit
class SliderCell: UITableViewCell {
// Interface Links
@IBOutlet weak var slider: UISlider!
@IBOutlet weak var progressLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
And here is the Controller:
import UIKit
// Table View with Dynamic Cells
class MainViewController: UITableViewController {
var sliderCell: SliderCell!
override func viewDidLoad() {
super.viewDidLoad()
sliderCell = SliderCell()
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch indexPath.row {
// Row 0 - My Slider
case 0:
let cell = tableView.dequeueReusableCell(withIdentifier: "sliderCell", for: indexPath) as! SliderCell
return cell
default:
return UITableViewCell()
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
// Set the height for slider cell to 200 pixels
switch indexPath.row {
case 0:
return 200
default:
return 200
}
}
// Reflect the value of Slider to ProgressLabel
@IBAction func sliderValueChanged(_ sender: UISlider) {
var currentValue = Int(sender.value)
let stepSize:Int = 10
currentValue = (currentValue - currentValue % stepSize)
DispatchQueue.main.async {
self.sliderCell.progressLabel.text = "\(currentValue)%"
}
}
}
Thanks in advance if you are reading this !
Upvotes: 0
Views: 335
Reputation: 100503
Don't add a reference to your cell here
sliderCell = SliderCell()
but use a delegate in cellForRowAt like
let cell =
cell.delegate = self
then inside the cell send anything with
delegate?.sendSliderValue()
you can also add slider action implementation inside the vc like
let cell = //
cell.slider.addTarget ////
cell.slider.tag = indexPath.row
@objc func sliderChanged(_ slider:UISlider) {
print(slider.value,slider.tag)
if let cell = tableView.cellForRow(at:IndexPath(row:slider.tag,section:0)) as? SliderCell {
var currentValue = Int(sender.value)
let stepSize:Int = 10
currentValue = (currentValue - currentValue % stepSize)
cell.progressLabel.text = "\(currentValue)"
}
// or
if let cell = tableView.visibleCells.first as? SliderCell {
//////
}
}
Upvotes: 1