Lens C View for communication with the controller

What is the correct way to accept user input in a view and then pass it to this controller? I know that NotificationCenter is one of the options, but, of course, is there a more elegant way to transfer data from a view to its controller?

All help is much appreciated and I always accept the answer!

0
source share
5 answers

Are you looking for Delegation or Data Source . You can see more information about this here, Delegation and data sources

A brief example of this would be something like 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 title of the class to which you want to delegate MyViewSubclass , you need to comply with the MyViewSubclassDelegate protocol.

  #import "MyViewSubclass.h" @interface MyViewController : UIViewController <MyViewSubclassDelegate> 

In @implementation MyViewController. use the MyViewSubclassDelegate method -(void)didTouchView .

When you initialize and create your MyViewSubclass object, you set MyViewController as a delegate:

 myViewSubclass.delegate = self // Self being MyViewController. 

In your MyViewSubclass , when you are ready to redirect any information or just want to run a method that you would do [self.delegate didTouchView]

Hope this helps!

+1
source

Use the delegate protocol design pattern or target action by subclassing UIControl . Think about how UIButton tells the view controller that it has been clicked. In the interface builder, you connect an action - a selector of type touchUpInside: to the target is the view controller to which it belongs. In non-IB, you explicitly UIButton which selector and which purpose to use.

Both methods make sense in different cases. For example, for UITextField it makes sense to use delegation, because a text field can send you any number of events, for example, when a user starts editing, finishes editing, or types a character.

It makes sense for the button to use the target action, because in fact there is only one event, expressed in different forms.

To scroll and drag and other gestures, use UIGestureRecognizer s.

+2
source

You are looking for delegation , where the controller is installed as the delegate of the view. You know this from the UITableViewDelegate.

+1
source

Subclass your UIControl and implement the target / action design template - use the sendActionsForControlEvents: method to sendActionsForControlEvents: controller.

0
source

Often UIKit objects, such as UITextField , have delegation methods that you can implement to execute your business logic. For example, UITextField has a delegation method called - textFieldDidEndEditing: which is called after the user rejects the keyboard.

0
source

All Articles