无法在 UIViewController 子类上设置标题



我遇到了以下问题。

我已经创建了一个自定义视图控制器,它有一些我需要的有用方法。

这是.h 中的代码

@interface MYViewController : UIViewController
- (void)method;
- (void)otherMethod;
@end

这是我的MYViewController类的init方法:

- (instancetype)init
{
    self = [super init];
    return self;
}

然后,当我试图扩展该类时,我无法设置子控制器的标题。例如,在"MYOtherController.h"中

@interface MYOtherViewController : MYViewController
- (void)childControllerMethod;
@end

这是MYOtherViewController的初始化:

- (instancetype)init
{
    self = [super init];
    return self;
}

然后,如果我实例化一个MYOtherViewController对象并尝试设置标题,则不会发生任何事情。例如:

MYOtherViewController *controller = [[MYOtherViewController] alloc] init];
controller.title = @"Hello";

如果我把它放在MYOtherViewController类的viewDidLoad中,它会记录标题为nil:

- (void)viewDidLoad {
    NSLog(@"title: %@", self.title);
    [super viewDidLoad];
}

为什么不能在这个子类中设置标题?

在alloc init之后还没有创建视图控制器的标题,您需要在viewDidLoad(即所有UI元素都已初始化的时候)之后设置它,所以您可以在alloc初始化之后设置的视图控制器上创建一个@property,然后在viewDidRoad中,将标题设置为@property 的值