【问题标题】:Custom Initialization for a View Controller using Storyboards使用 Storyboard 对视图控制器进行自定义初始化
【发布时间】:2012-10-20 07:39:14
【问题描述】:

我是故事板的新手,在自定义初始化方面遇到问题。

在使用故事板之前,我曾经这样做是从具有自定义初始化的表中推送视图控制器:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    //Creating Dummy Hotel
    HotelItem *hotel = [[HotelItem alloc] init];

    HotelDetailViewController *controller = [HotelDetailViewController controllerWithHotel:hotel];
    controller.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:controller animated:YES];

    [hotel release];
}

现在有了故事板,我使用的是 prepareForSegue 而不是 didSelectRowAtIndexPath,它变成了这样:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{

    //Creating Dummy Hotel
    HotelItem *hotel = [[HotelItem alloc] init];
    hotel.name = @"Hotelucho";

    // Make sure we're referring to the correct segue
    if ([[segue identifier] isEqualToString:@"ShowSelectedHotel"]) {

        HotelDetailViewController *controller = [segue destinationViewController];

    }
}

我知道我可以更改我的私有变量“hotel”并在 [segue destinationViewController] 之后设置属性,但我发现调用我的自定义 init 方法更有用。

有没有办法做到这一点?

【问题讨论】:

    标签: iphone uiviewcontroller storyboard uitableview


    【解决方案1】:

    如果您有大量代码需要在初始化后执行,您可能需要为其创建一个单独的方法,然后在 initWithCoder:initWithFrame: 中调用该方法。

    查看此答案以获取更多信息: Objective C - Custom view and implementing init method?

    【讨论】:

    • 但是关于我上面发布的代码。如果我在 initWithCoder 和 initWithFrame 中进行了初始化,我如何像在“controllerWithHotel:”中那样通过这些方法发送酒店变量?
    • 在您的 prepareForSegue:: 方法中,只需在您的控制器对象上设置属性。设置属性后不要忘记刷新需要刷新的任何内容。
    • 所以我不能将我的酒店财产保密,因为我不能使用像 controllerWithHotel 这样的自定义初始化:对吗?
    • 另外,设置属性后刷新任何内容是什么意思?在此先感谢:)
    • 对,应该是公共财产。至于第二个问题,你的 init 方法会在你设置属性之前被调用。因此,例如,如果您设置 UILabel 值,它不会反映您在设置属性时所做的更改。在这种情况下,只需删除 init 中调用的方法并在 viewDidAppear: 或您认为必要的任何地方调用它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-14
    • 2013-08-05
    • 2013-08-29
    • 2012-03-03
    • 2014-11-12
    相关资源
    最近更新 更多