How to send the text from textfield to another cla

2019-08-04 15:28发布

问题:

In my app Iphone, I want to do a simple thing like : I have a GroupDetailViewController with a text Field and a button. When user press the button I want to send the text from textfield to another class ItemViewController and set this text to a label. I have no idea how can I do this. I am new on Iphone,I have done just some tutorials. I have looked here : How to send text field value to another class but I dont understand the answer. Can anyone explain me or give me an example?

回答1:

Let us assume that your second class is SecondViewController.
Now in SecondViewController declare one NSString and set its properties.

SecondViewController.h

NSString *strTextValue;  

....  

@property(nonatomic,retain) NSString *strTextValue; 

SecondViewController.m

@synthesize strTextValue;

Now in GroupDetailViewController, on button touch event, put the value from textfield in strTextValue.

-(IBAction)ButtonMethod:(id)sender
{
SecondViewController *controller = [[SecondViewController alloc]init];
controller.strTextValue = [txtField text];  
//Navigate to SecondViewController
}  

Put strTextValue in label created in SecondViewController

SecondViewController.m

lbl.text = strTextValue;


回答2:

Quick Solution:

Create a shared application delegate and set the value to a string in delegate and reuse it. 1) create an NSString variable say passVal and synthesize it in youtAppDelegate file. 2) In GroupDetailViewController

yourAppDelegate *del=[[UIApplication SharedApplication]delegate];
del.passVal=textField.text;

3) In ItemViewController

yourAppDelegate *del=[[UIApplication SharedApplication]delegate];
label.text=del.passVal;