使用xibs,您可以调用不同的初始化程序:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Fetch Note...
    // Initialize Edit Note View Controller with the fetched Note
    EditNoteViewController *vc = [[EditNoteViewController alloc] initWithNote:note];

    // Push View Controller onto Navigation Stack
    [self.navigationController pushViewController:vc animated:YES];
}

这使我可以将变量(在EditNoteViewController中)保持 private 状态,并且还可以为某些变量设置默认值,例如
- (id)initWithNote:(Note *)note {
    // ....
    if (self) {
        self.note = note;
        self.isEditing = YES;
    }
    return self;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    //...
    if (self) {
        self.isEditing = NO;
    }
    return self;
}

我现在正在尝试使用情节提要:
  • 是否有一个很好的方法可以从prepareForSegue设置变量而不暴露变量或任何其他实现?
  • 如何设置默认值?

  • 请尽可能明确

    最佳答案

    您应该使用prepareForSegue。仅在接收View Controller中公开您需要的内容

    - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Prepare for next view controller
      if ([segue.identifier isEqualToString:@"someThing"]) {
        SomeThingViewController *viewController = segue.destinationViewController;
        viewController.someProperty = @"something else";
      }
    }
    

    属性someProperty将需要在SomeThingViewController的标头中公开
    @property (nonatomic, strong) NSString *someProperty;
    

    要设置默认值,请检查接收视图控制器的viewDidLoad中的属性值
    if (someProperty==nil) someProperty = @"Default";
    

    关于iphone - 从xib移到 Storyboard 时的封装?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17184061/

    10-10 16:07