Search code examples
iosuitextviewpushviewcontrolleruitextviewdelegate

ios Passing TextView from PushView to PresentingView


I am trying to do the following, and not able to find a straightforward answer.. It is related to this :Passing uitextfield from one view to another. But not exactly.

I have a Firstview.m, from which I push to a Secondview.m. The Secondview.m has a UITextView. I allow the user to edit the UITextView on Secondview.m. Now I want to store this text value in a variable in Firstview.m. One way to to do this is as follows

in Firstview.h

@property (nonatomic) Secondview *secondView;

That is keep a secondView variable in Firstview itself. But this doesn't seem efficient. Ideally I should only have 1 NSString text field in FirstView. What is the right way to do this ? Thanks


Solution

  • You can achieve this by using Delegation in Objective-C.

    In your SecondView.h add following right after Header Inclusion

    @protocol YourDelegateName <NSObject>
       -(void)setText:(NSString *)strData;
    @end
    

    Also add delegate property to your header for accessing them in calling class, like below (This goes with other properties declaration in SecondView.h file):

    @property (nonatomic, weak) id<YourDelegateName> delegate;
    

    Now, Comes the calling the delegate part. Say, you want to save the text value of UITextView of SeconView in strTextViewData of FirstView class, when the following event occurs:

    - (IBAction)save:(id)sender
    {
        [self.delegate setText:self.txtView.text]; // Assuming txtView is name for UITextView object
    }
    

    Now, In FirstView.h add YourDelegateName in delegate list like below:

    @interface FisrtView : ViewController <YourDelegateName>
        @property (nonatomic, reatin) NSString *strTextViewData;
    @end
    

    And then in FisrtView.m file when you create instance of SecondView class, set delegate to self like below:

    SecondView *obj = [[SecondView alloc] initWithNibName:@"SeconView" bundle:nil];
    obj.delegate = self; // THIS IS THE IMPORTANT PART. DON'T MISS THIS.
    

    Now, Implement the delegate method:

    -(void)setText:(NSString *)strData
    {
         self.strTextViewData = strData;
    }
    

    Applying this to your code will do what you want. Also, Delegation is one of the most important feature of Objective-C language, which - by doing this - you will get to learn.

    Let me know, if you face any issue with this implementation.