问题
I connected a IBOutlet
and IBAction
to my button variable from Interface Builder to my View Controller. How do I add an action method to the button in Swift?
This code doesn't seem to work.
@IBOutlet var OK: UIButton!
@IBAction func OK(sender: UIButton){}
The Objective-C equivalent I found is:
@interface Controller
{
IBOutlet id textField; // links to TextField UI object
}
- (IBAction)doAction:(id)sender; // e.g. called when button pushed
回答1:
When you attach a button to the viewController
, and create an action (IBAction
) using ctrl-drag, you create a method (also called a function) that looks likes this in Swift (if it dose not have arguments):
@IBAction func buttonAction() {}
In objective-C the same thing will look like this:
- (IBAction)buttonAction {}
So that means that @IBAction func OK(sender: UIButton){}
is an action method.
If you want to know about the sender argument, I would recommend this SO post.
Edit:
For what you want to do, I create an IBOutlet
and an IBAction
, that way I can change it's attributes with the outlet variable, and have the action side of things with the IBAction
, like what you show above:
@IBOutlet var OK: UIButton!
@IBAction func OK(sender: UIButton){}
For example, if I want to hide the button, I would put this code in the viewDidLoad
OK.hidden = true
The OK in that code is for the outlet variable, if I wanted to print "You pressed me" to the console when the button is pressed, I would use this code:
@IBAction func OK(sender: UIButton){
println("You pressed me")
}
Above I am using the action to print "You pressed me" to the console.
A few things to note:
When Swift 2.0 gets released println
will get changed to print
. Also with you action and outlet, I would suggest giving them differing names, to make it easier to differentiate the two, something like this:
@IBOutlet var okOutlet: UIButton!
@IBAction func okAction(sender: UIButton){}
Along with that, you should use camel case when naming variables, constants, functions, etc.
回答2:
One way to do it, is control-drag from your button to your viewcontroller and choose action:
If you have connected your button's action, your code should work just fine.
回答3:
Here are the steps you can follow-
For @IBOutlet
1.Declare Your Interface builder Element property right after class name
class SomeViewController: UIViewController{
@IBOutlet weak var aTextField : UITextField! ////Your Interface builder Element
2.Hook the IB Element From Storyboard.
For @IBAction
1.Write A method inside your class(say SomeViewController
)
@IBAction func anAction(_sender : AnyObject){
}
2.Hook the method from Storyboard.
Hope it might helps.
回答4:
You can simply add action from your storyboard. See the image.
来源:https://stackoverflow.com/questions/32572305/iboutlet-and-ibaction-in-swift