我已经设置了一个基本的测试应用程序,它显示一个包含标签的视图,不使用 IB。我想使用自定义 UIView 子类和自定义 UIViewController 子类。
这将按预期运行,但 MyViewController 的 viewWillAppear 和其他类似的委托不会触发。
我缺少什么来制造这些火?在以前的项目中(使用 IB),这些会很好。
这是完整的代码:
AppDelegate - 加载一个“MainVC”视图控制器并将其设置为根控制器
#import "AppDelegate.h"
#import "MainVC.h"
@implementation AppDelegate
@synthesize window = _window;
@synthesize mainVC = _mainVC;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.mainVC = [[MainVC alloc] init];
self.window.rootViewController = self.mainVC;
[self.window makeKeyAndVisible];
return YES;
}
MainVC - 创建一个分配“MyView”的“MyViewController”(它还传递应该用于视图的帧大小)
#import "MainVC.h"
#import "MyViewController.h"
@implementation MainVC
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
MyViewController *controller = [[MyViewController alloc] init];
CGRect frame;
frame.origin.x = 5;
frame.origin.y = 5;
frame.size.width = self.view.frame.size.width - (2 * 5);
frame.size.height = self.view.frame.size.height - (2 * 5);
controller.startingFrame = frame;
[self.view addSubview:controller.view];
}
return self;
}
MyViewController - 创建 MyView
#import "MyViewController.h"
#import "MyView.h"
@implementation MyViewController
@synthesize startingFrame;
- (void)loadView{
self.view = [[MyView alloc] initWithFrame:startingFrame];
}
- (void)viewWillAppear:(BOOL)animated{
NSLog(@"appearing"); //doesn't do anything
}
- (void)viewDidAppear:(BOOL)animated{
NSLog(@"appeared"); //doesn't do anything
}
我的观点
#import "MyView.h"
@implementation MyView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.backgroundColor = [UIColor whiteColor];
label = [[UILabel alloc] initWithFrame:CGRectMake(20, 20, 150, 40)];
[label setText:@"Label"];
[self addSubview:label];
}
return self;
}