Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
505 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 Reply

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
     }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...