Change label from a different view [closed]

2019-07-02 15:57发布

This is mainly a delegation question because I'm still learning and don't get it. I don't know how to go about creating the delegate I need.

I know similar questions have been asked but the solutions don't help me out. How can I switch the text of a label on View 1 with the contents of a UITextField from View 2?

Thanks!

1条回答
\"骚年 ilove
2楼-- · 2019-07-02 16:17

In this code snippet, ChildViewController is your View2 and ParentViewController is your View1.

In your ChildViewController.h file:

@protocol ChildViewControllerDelegate <NSObject>
- (void)parentMethodThatChildCanCall:(NSString *)string;  //pass back the string value from your textfield
@end

@interface ChildViewController : UIViewController 
{
    @property (weak, nonatomic) IBOutlet UITextField *myTextField;
}
@property (assign) id <ChildViewControllerDelegate> delegate;

In your ChildViewController.m file:

@implementation ChildViewController
@synthesize delegate;

// Some where in your ChildViewController.m file
// to call parent method:
//  [self.delegate parentMethodThatChildCanCall:myTextField.text];

In ParentViewController.h file:

@interface parentViewController <ChildViewControllerDelegate>
{
    @property (strong, nonatomic) IBOutlet UILabel *myLabel;
}

In ParentViewController.m file:

//after create instant of your ChildViewController

childViewController.delegate = self;

- (void) parentMethodThatChildCanCall:(NSString *)string
{
  // assign your passed back textfield value to your label here
    myLabel.text = string;
}
查看更多
登录 后发表回答