Im new to Objective-C & iOS programming so Im very confused about event and action handling. I don’t really understand what is the difference between connecting a button in Interface builder with its files owner method (for instance connecting button action pressed with my personal method buttonClicked) and on the other hand creating a delegate which will respond to button events? I am confused because I come from C# (.NET) and there you only handling events via delegation.
Share
Let’s create event handling programmatically first. Some assumptions …
MyViewControllermyButton(UIButton *)First step is to create method to handle your button taps:
Add tap event handling:
What this code does?
selfin this case is instance ofMyViewControllerclass, which is going to handle touch up inside event (addTarget).actionis method which will be called whenUIControlEventTouchUpInsidefires.So the
addTarget:...line adds event handling and when the control event fires, this …… will be called automatically.
It’s simplified example, it can be more complicated in the real world:
UIButtonin separateUIView(good practice, I dislike when people put them inUIViewController)senderargument)And now back to outlets. Outlet is just an automatic glue for
addTarget:....UIButtonis subclass ofUIControland here you can see how other events can be handled and what events you can handle.Delegation is also common practice, but not for
UIControl. There’s no delegate, etc. You have to do it in this way.Or you can enhance
UIButtonto handle events via blocks for example. Here’s one way https://gist.github.com/2468899 or you can Google for more.