嘗試在第一頁按鈕點擊時,直接修改第二頁 UINavigationBar outlet 的 topItem.title,但第二頁尚未載入導致崩潰或無效果。
// 第一頁
- (IBAction)ChangeSecondPageTitle:(id)sender {
SecondViewController *second = [self.storyboard instantiateViewControllerWithIdentifier:@"second"];
second.detailTitle.topItem.title = @"example"; // 錯誤:detailTitle 尚未連接,topItem 為 nil
[self presentModalViewController:second animated:YES];
}
遵循 MVC:第一頁傳遞「標題字串」模型資料,第二頁在 viewDidLoad 套用到視圖。
// 第一頁:準備轉場傳值
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:@"showDetail"]) {
SecondViewController *vc = segue.destinationViewController;
vc.navBarTitle = @"example"; // 傳遞字串屬性
}
}
// 第二頁:接收並套用
@property (strong, nonatomic) NSString *navBarTitle;
- (void)viewDidLoad {
[super viewDidLoad];
self.title = self.navBarTitle; // 自動設定 navigationItem.title
}
// 第一頁
- (IBAction)ChangeSecondPageTitle:(id)sender {
SecondViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"second"];
vc.navBarTitle = @"example";
// 若在 NavigationController 中:
[self.navigationController pushViewController:vc animated:YES];
// 或模態呈現:
UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
[self presentViewController:nav animated:YES completion:nil];
}
// 第二頁同方法一
self.title 或 self.navigationItem.title 設定導航標題,系統自動處理 navigationBar 顯示。掌握「資料下傳、視圖自繪」的單向流,是 iOS 畫面轉場傳值的基石。