What is the proper way to accept user input in a view and then transfer it to that view's controller? I know the NotificationCenter is one option, but surely there is a more elegant way to transfer data from a view to its controller?
All help is greatly appreciated and I always accept an answer!
You're looking for Delegation
or a Data Source
. You can see more information about this here, Delegation and Data Sources
A brief example of this would be, something along the lines of this:
//MyViewSubclass.h
@protocol MyViewSubclassDelegate
//Implement your delegate methods here.
-(void)didTouchView;
@end
@interface MyViewSubclass {
id<MyViewSubclassDelegate>delegate;
}
@property(nonatomic,assign)id<MyViewSubclassDelegate>delegate;
Of course, @synthesize
your delegate
in MyViewSubclass.m
Now in the class's header, that you want the delegate of MyViewSubclass
to be, you need to conform to the `MyViewSubclassDelegate Protocol.
#import "MyViewSubclass.h"
@interface MyViewController : UIViewController <MyViewSubclassDelegate>
In your @implementation
of MyViewController.
, implement the MyViewSubclassDelegate
method of -(void)didTouchView
.
When you initialize and create your MyViewSubclass
object, you set MyViewController
as the delegate:
myViewSubclass.delegate = self // Self being MyViewController.
In your MyViewSubclass
, when you're ready to forward any information, or simply want to fire a method you would do [self.delegate didTouchView]
Hope this helps !
Use the delegate protocol design pattern, or target-action by subclassing UIControl
. Think about how a UIButton
tells a view controller that it's been pressed. In interface builder, you connect an action - a selector something like touchUpInside:
to a target - the view controller that owns it. In non-IB, you directly tell the UIButton
what selector and what target to use.
Both methods make sense in different cases. For a UITextField
, for example, it makes more sense to use delegation because it's possible for the text field to send you any number of events, such as an event when the user begins editing, ends editing, or types a character.
For a button, it makes more sense to use target-action because there's really only one event expressed in different forms.
For swipes and drags and other gestures, use UIGestureRecognizer
s.
You are looking for delegation, where the controller set itselfs as the delegate of the view. You know it from UITableViewDelegate.
Make your view a subclass of UIControl
and implement the target/action design pattern - use the sendActionsForControlEvents:
method to message the controller.
Often the UIKit objects like UITextField
have delegate methods that you can implement to perform your business logic. E.g UITextField has a delegate method called - textFieldDidEndEditing:
that gets called after the user has dismissed the keyboard.