luke luke - 5 months ago 32
iOS Question

'sliderChanged: unrecognized selector sent to instance'

I have created a slider and a text label to display the value of the slider. Both done programmatically:

class FilterCell: UITableViewCell {

override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)

required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")

let slider : UISlider = {
let slider = UISlider()
slider.minimumValue = 0
slider.maximumValue = 50
slider.value = 50
slider.continuous = true
slider.userInteractionEnabled = true
slider.translatesAutoresizingMaskIntoConstraints = false
return slider

var distanceLabel : UILabel = {
let label = UILabel()
label.text = "Distance: 50km"
label.font = UIFont.systemFontOfSize(15.0)
label.textColor = UIColor.blackColor()
label.translatesAutoresizingMaskIntoConstraints = false
return label

func sliderChanged(sender: UISlider) {
var sliderValue = sender.value
distanceLabel.text = "Distance: \(sliderValue)km"

inside my tableview I call the function to change the value of the slider:

func tableView(tableView:UITableView, cellForRowAtIndexPath indexPath:NSIndexPath) -> UITableViewCell {

let cell = tableView.dequeueReusableCellWithIdentifier(filterCellId) as! FilterCell
cell.slider.addTarget(self, action: #selector(FilterCell.sliderChanged(_:)), forControlEvents: .ValueChanged)

return cell


The slider and the label display fine. When I interact with the slider to change the value, it crashes and 'sliderChanged:]: unrecognized selector sent to instance 0x7fb06d0df040'.


Try add target to cell, not self

cell.slider.addTarget(cell, action: #selector(FilterCell.sliderChanged(_:)), forControlEvents: .ValueChanged)