Thursday, May 7, 2015

IBAction IBOutlet

IBAction and IBOutlet are macros defined to denote variables and methods that can be referred to in Interface Builder.
IBAction resolves to void and IBOutlet resolves to nothing, but they signify to Xcode and Interface builder that these variables and methods can be used in Interface builder to link UI elements to your code.
If you're not going to be using Interface Builder at all, then you don't need them in your code, but if you are going to use it, then you need to specify IBAction for methods that will be used in IB and IBOutlet for objects that will be used in IB.

IBAction and IBOutlet
Gone are the days of switching back and forth between .h and .m files! And one of the tangible benefits of a single file per class is easy access to IBAction and IBOutlet declarations.
In Objective-C your .h would probably have a bit of this:
@interface MyViewController: UIViewController

@property (weak) IBOutlet UIButton *likeButton;
@property (weak) IBOutlet UILabel *instructions;
- (IBAction)likedThis:(id)sender;

@end
And then you constantly have to dig into your .h file when playing with storyboards to tweak names. Blah.
Simplicity rules in swift. If you have a property defined that you want to make accessible to your storyboards, just add the @IBOutlet attribute before your property. Similarly with @IBAction to connect storyboard actions back to code.
class MyViewController: UIViewController {
  @IBOutlet weak var likeButton: UIButton?
  @IBOutlet weak var instruction: UILabel?

@IBAction func likedThis(sender: UIButton) {}
}
There are other interesting attributes that you can apply in swift but for now we’ll just cover these two common interface builder ones. There are two new interface builder attributes @IBDesignable and@IBInspectable which we probably won’t cover as their usage is very similar to this.

No comments: