Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
481 views
in Technique[技术] by (71.8m points)

ios - UISwitch in accessory view of a tableviewcell, passing a parameter with the selector to have selector function see the indexpath.row?

I have a UISwitch in a tableviewcontroller, and when the switch is toggled I want it to change the value of a boolean variable in an array I created inside the view controller, that the cell is related to. Kind of like the Stock Alarm App on IOS, where each cell has a UISwitch, and toggling the switch will turn off each individual alarm. So with the UISwitch, with its selector code, this is inside the cellForRowAtIndexPath method

//switch
    let lightSwitch = UISwitch(frame: CGRectZero) as UISwitch
    lightSwitch.on = false
    lightSwitch.addTarget(self, action: #selector(switchTriggered), forControlEvents: .ValueChanged)
    //lightSwitch.addTarget(self, action: "switchTriggered", forControlEvents: .ValueChanged )

    cell.accessoryView = lightSwitch

I want it to do this

func switchTriggered(a: Int) {
    changeValueOfArray = array[indexPath.row]
}

I don't have the code written for that part yet, but my question is, How can i let the switchTriggered function see the indexPath.row value, without passing it as an argument to the function because I can't because its a selector?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
let lightSwitch = UISwitch(frame: CGRectZero) as UISwitch
    lightSwitch.on = false
    lightSwitch.addTarget(self, action: #selector(switchTriggered), forControlEvents: .ValueChanged)
    lightSwitch.tag = indexpath.row
    cell.accessoryView = lightSwitch

Let save your boolean value in Array

    func switchTriggered(sender: UISwitch) {
      sender.on ? array[sender.tag]=1 : array[sender.tag]=0
     }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...