Passing NSString from one view to another view
I have 2 views that are sharing the same class files (.h and .m). In the first view, I have a UIPicker with a list of items and a button. If the user clicks the button, I want my second view to come up with the appropriate Picture开发者_C百科 (based on the item that was selected in the UIPicker).
My thinking was to set an NSString in the first view based on the selected item. Then when the user clicks the button to push the second view onto the screen, i could pass that string with the new view. I've been "googling" for awhile but I can't seem to wrap my finger around it. If it matters, I am using a Navigation Controller. Here is the code that is executed on the button click:
-(IBAction) viewPictures{
ViewControllerClass *sView = [[ViewControllerClass alloc] initWithNibName:@"ViewController2XIB" bundle:nil];
[self.navigationController pushViewController:sView animated:YES];
}
You can either add an NSString * property to the ViewControllerClass and set it after you init it (this would be the easiest), or you can create your own init method that takes a string and sets it there.
Option 1:
(place this in your .h file)
@interface ViewControllerClass : UIViewController {
NSString *someString;
}
@property (nonatomic, copy) NSString *someString;
@end
(Then in your .m file)
@implementation ViewControllerClass
@synthesize someString;
@end
Alter your code from above to this:
-(IBAction) viewPictures{
ViewControllerClass *sView = [[ViewControllerClass alloc] initWithNibName:@"ViewController2XIB" bundle:nil];
sView.someString = @"Whatever String you want";
[self.navigationController pushViewController:sView animated:YES];
}
Option 2:
(place this in your .h file)
@interface ViewControllerClass : UIViewController {
NSString *someString;
}
- (id)initWithNibName:(NSString *)nibName bundle:(NSBundle *)nibBundle someString:(NSString *)SomeString;
@end
(Then in your .m file)
@implementation ViewControllerClass
- (id)initWithNibName:(NSString *)nibName bundle:(NSBundle *)nibBundle someString:(NSString *)SomeString
{
if(self = [super initWithNibName:nibName bundle:nibBundle]) {
someString = [SomeString copy];
}
return self;
}
@end
Alter your code from above to this:
-(IBAction) viewPictures{
ViewControllerClass *sView = [[ViewControllerClass alloc] initWithNibName:@"ViewController2XIB" bundle:nil someString:@"Whatever String you want"];
[self.navigationController pushViewController:sView animated:YES];
}
Put a NSString in the .m that shares these 2 views, like Chris said. In the method that responds to the button click pass the string from the uipicker to the NSString you created and then pass it to the view 2.
精彩评论