Passing NSString from one view to another view

倖福魔咒の 提交于 2019-12-04 19:00:02

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.

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