Reputation: 71
How can I execute a piece of code (HTML request)?
task.resume()
How can execute that when I change a switch (like from true
to false
and from false
to true
)?
I don't want to use a loop because I only want 1 request on change.
Upvotes: 2
Views: 4963
Reputation: 12615
You can also do it programmatically with the addTarget() method of the UIControl class (of which UIButton and other controls on iOS are subclasses). The UIControl class basically is the class that adds events and dispatch to UIViews, which is why it is so useful when you're creating your own custom widgets - because you simply get the ability to let consumers create event notification receivers for your widget and lets your widget easily dispatch events to those consumers without requiring much extra coding work on your part in either case.
The @IBAction mechanism is a convenience when using Interface Builder, but it does the same thing transparently. The advantage is it makes your code more self documenting. If you see IBAction in front of a method you immediately know it is an event (e.g. "action") handler. However as time rolls on you'll find you're using addTarget() so much that the hassle of doing it with Interface Builder isn't worth it, and you'll just memorize it, much like someone memorizes how to programmatically create events in javascript.
Upvotes: 2
Reputation: 601
Make an IBAction
function to the switch. Put the code you want to run in there.
@IBAction func switchButtonChanged (sender: UISwitch) {
//Put your code here
}
Whenever the switch is changed, the function will run. If your using Storyboards, make sure to link the function to the UISwitch
.
You may also want to use mySwitch.on
(returns a Boolean value, true if on, false if off) to do other things.
Upvotes: 11