I'm creating an app in UIKit, programmatically. One screen has a UITableView with custom cells, some have sliders inside. All cells show up and can be selected. Other custom cell elements like buttons and text field react to interaction, but not the sliders. Here's my code:
class CellWithSliderValues: UITableViewCell{
@IBOutlet var slider: UISlider! = {
let ctrl = UISlider()
// color setup here
return ctrl
}()
// some labels
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.addSubview(slider);
// layout code, skipped for StackOverflow
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
How the cell is created for the table, with tag calculation skipped:
let cell = mainScreen.table.dequeueReusableCell(withIdentifier: "CellWithSliderValues") as! CellWithSliderValues
cell.slider.maximumValue = Constants.BEST
cell.slider.minimumValue = Constants.WORST
cell.slider.value = currvalue
// tag is set here
cell.slider.addTarget(self, action: #selector(sliderChange), for: .valueChanged)
return cell
Part of the delegate that is called when clicking of the slider cell:
guard let cell = (mainScreen.table.cellForRow(at: indexPath) as? CellWithSliderValues) else {return}
cell.slider.becomeFirstResponder()
return
Finally, the function that should be called when the slider is dragged but is never actually called (seen with breakpoints):
@objc func sliderChange(sender: UISlider){
// get the values here
sender.resignFirstResponder()
}
The same approach did work with the text entry fields, so what am i doing wrong here? Is it because of the Slider not having delegates?
CodePudding user response:
Commenter Sulthan's solution of adding a slider as a subview to the cell.contentView instead of the the cell directly worked like a charm.
self.contentView.addSubview(slider);
I wonder why didn't other cell elements require that.