从不同的视图控制器更改导航栏文本

时间:2012-07-12 01:33:37

标签: ios objective-c uiviewcontroller uitextfield

我在此之前发布了一个类似的问题,但我现在有一个更明确的问题和更多信息以及代码。我目前有一个带有UITextField和UIButton的ViewController(SignUpViewController)。我还有另一个具有UINavigationBar的ViewController(ProfileViewController)。我希望能够在SignUpViewController的TextField中键入用户名,点击UIButton,然后让ProfileViewController中的naviBar文本设置为SignUpViewController的TextField中的文本。问题是,我无法从ProfileViewController访问UITextField。我目前在我的AppDelegate中有一个名为“titleString”的NSString,我试图将其用作某种解决方案。下面是我的代码,如果我的问题完全抛弃了你,因为这有点难以解释堆栈溢出:

SignUpViewController:

- (IBAction)submitButton {

     ProfileViewController *profileVC = [[ProfileViewController alloc] initWithNibName:nil bundle:nil];
     [self presentViewController:profileVC animated:YES completion:nil];

     AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
     appDelegate.titleString = @"Profile";

     appDelegate.titleString = usernameTextField.text;

}

- (void)viewDidLoad {

     AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];

     [super viewDidLoad];
 }

ProfileViewController:

- (void)viewDidLoad {

     AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
     self.title = appDelegate.titleString;

     [super viewDidLoad];
}

一切正常,直到我点击SignUpViewController中的submitButton。这是怎么回事?

1 个答案:

答案 0 :(得分:1)

你可以在这里做几件事来在视图控制器之间传递数据。

1)设置委托方法。 profileViewController将是signInViewController的委托。当按下登录按钮时,signInViewController调用profileViewController正在侦听的委托方法,该方法将标题传递给profileViewController。

在signInViewController.h中:

@protocol SignInDelegate

@required
- (void)didSignInWithTitle:(NSString*)title;

@end

@interface SignInViewController : UIViewController

@property (nonatomic, assign) id<SignInDelegate> delegate;

然后在分配时将您的ProfileViewController设置为委托:

signInViewController.delegate = profileViewController

这是你的ProfileViewController.h:

#import "SignInViewController.h"

@interface ProfileViewController : UIViewController <SignInDelegate>

最后,确保你的ProfileViewController实现 - (void)didSignInWithTitle:(NSString *)标题;方法

2)您可以使用NSNotificationCenter发布附加标题的自定义通知。如果您有其他几个想要像配置文件一样设置标题的viewControllers,这将非常有用。

#define UPDATE_NAVBAR_TITLE @"UPDATE_NAVBAR_TITLE"

当signInViewController完成时:

[[NSNotificationCenter defaultCenter] postNotificationName:UPDATE_NAVBER_TITLE object:nil];

然后,确保将ProfileViewController添加为观察者:

[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(navbarUpdated) name:UPDATE_NAVBAR_TITLE object:nil];

对于你所问的我推荐第一个。祝你好运!