Gần đây tôi đã thử làm việc với MainStoryboard.storyboard trong Xcode và cho đến nay Nó sẽ khá tốt và tôi tự hỏi tại sao tôi chưa bao giờ sử dụng nó trước đây. Trong khi chơi với một số mã tôi va vào một chướng ngại vật và tôi không biết làm thế nào để giải quyết điều này.Kịch bản và tùy chỉnh init
Khi tôi alloc và init một ViewController mới (với một init tùy chỉnh Tôi tuyên bố trong lớp ViewControllers) tôi sẽ làm một cái gì đó như thế này:
ViewController *myViewController = [[ViewController alloc] initWithMyCustomData:myCustomData];
Sau đó, sau đó tôi có thể làm một cái gì đó như:
[self presentViewController:myViewController animated:YES completion:nil];
Khi tôi đang làm việc với bảng phân cảnh tôi đã học được rằng việc chuyển sang một ViewController độc lập yêu cầu Mã định danh.
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
ViewController *myViewController = [storyboard instantiateViewControllerWithIdentifier:@"MyViewControllerIdentifier"];
[self presentViewController:myViewController animated:YES completion:nil];
Làm cách nào tôi vẫn có thể sử dụng tùy chỉnh khởi tạo cho myViewController trong khi sử dụng bảng phân cảnh?
Is it ok để chỉ làm một cái gì đó như thế này:
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
ViewController *myViewController = [storyboard instantiateViewControllerWithIdentifier:@"MyViewControllerIdentifier"];
myViewController.customData = myCustomData;
[self presentViewController:myViewController animated:YES completion:nil];
//MyViewController.m
- (id) initWithMyCustomData:(NSString *) data {
if (self = [super init]) {
iVarData = data;
}
return self;
}
Cảm ơn. Có vẻ điên rồ mà Apple không cung cấp một cách để tạo ra một phương pháp 'init' tùy chỉnh thích hợp với Storyboards. – jowie
Tôi không chắc tại sao một người sẽ nói: "Nếu tất cả phương thức initWithCustomData của bạn làm là thiết lập một biến mẫu, bạn chỉ cần đặt nó theo cách thủ công (không có tùy chỉnh nội bộ hoặc các phương thức bổ sung cần thiết)". Không có tài liệu nào từ Apple tuyên bố rằng tôi khuyên bất kỳ độc giả nào xem xét tuyên bố này chỉ là một ý kiến và không phải là một quy tắc để tuân theo. Nhiều người khởi tạo trong iOS thậm chí chỉ cần một đối số. – zumzum
@zumzum Apple sử dụng thực hành thiết lập các biến trong phương thức 'preparForSegue: sender:' trong mã ví dụ của chúng. Xem tệp 'AddTimedReminder.m' trong [EKReminderSuite] (https://developer.apple.com/library/prerelease/ios/samplecode/EKReminderSuite/Introduction/Intro.html#//apple_ref/doc/uid/TP40015203- Intro-DontLinkElementID_2) ví dụ về dự án cho một ví dụ. –