how to pass text between views

喜夏-厌秋 提交于 2019-12-08 03:39:50

问题


i made 2 views and i want to send text of label on main view to sub view to an want to print it there on another label's text value.... how to pass that text


回答1:


I wouldn't use a singleton pattern or any other 'global variable'. This will make your view controllers very tightly coupled and restricts reusability. I would just create a instance variable in the second view controller and set this in the main one before presenting the view.

The second view controller then sets the label.text to the instance variable in (for example) viewDidLoad.

This way, the second view controller doesn't depend on any 'globals' or includes and will be more reusable.

//SecondViewController.h
@interface SecondViewController : UIViewController {
    NSString *theLabel;
}

@property(nonatomic, copy) NSString *theLabel; //Synthesize in implementation

@end

Then in the main view controller:

//Create instance of secondViewController
instanceOfSecondViewController.theLabel = @"Nut";
//Present the second view here



回答2:


If class A handle your view1 and Class B handle view2 then define a interfaces in class B to accept new label to your one of the UI element then call that interface from class A.




回答3:


Look into the Singleton pattern.

What should my Objective-C singleton look like?

Then you could do something like:

//view1 
#import "SingletonClass.h"
...
[SingletonClass sharedInstance].savedText = @"blah";

and

//view2
#import "SingletonClass.h"
...
lbl.text = [SingletonClass sharedInstance].savedText;


来源:https://stackoverflow.com/questions/3325159/how-to-pass-text-between-views

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!