【发布时间】:2014-09-03 11:02:26
【问题描述】:
我正在尝试对以编程方式创建的 UI 进行干净的实现。
我从我的AppDelegate.m开始
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
MainViewController *mainVC = [[MainViewController alloc] init];
UINavigationController *navC = [[UINavigationController alloc] initWithRootViewController:mainVC];
self.window.rootViewController = navC;
[self.window makeKeyAndVisible];
return YES;
}
那么MainViewController.m是UIViewController的子类实现如下:
- (void)loadView {
CGRect applicationFrame = [[UIScreen mainScreen] applicationFrame];
MenuView *contentView = [[MenuView alloc] initWithFrame:applicationFrame];
self.view = contentView;
}
而MenuView.m中的自定义UIView实现如下
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
NSLog(@"init got called");
NSLog(@"frame size %f %f", self.frame.size.width, self.frame.size.height);
self.backgroundColor = [UIColor greenColor];
}
return self;
}
...
- (void)loadView {
NSLog(@"loadView got called");
UIButton *newButton = [[UIButton alloc] init];
newButton.titleLabel.text = @"New Button";
newButton.backgroundColor = [UIColor blueColor];
[self addSubview:newButton];
NSDictionary *views = NSDictionaryOfVariableBindings(newButton);
[newButton setTranslatesAutoresizingMaskIntoConstraints:NO];
NSDictionary *metrics = @{@"buttonWidth": @(150), @"buttonHeight": @(150)};
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-(100)-[newButton(buttonWidth)]"
options:0 metrics:metrics views:views]];
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[newButton(buttonHeight)]-(100)-|"
options:0 metrics:metrics views:views]];
}
当我运行它时,模拟器显示一个绿屏 - 但没有按钮。 init 方法中的NSLogs 会触发并显示 320 x 548 的帧大小,但不会调用 loadView 方法。
我做错了什么?
谢谢
【问题讨论】:
-
我认为
loadView要求UIViewController子类而不是自定义UIView -
好的,我在哪里设置视图的子视图?
-
尝试在初始化期间调用此按钮创建方法,例如
- (id)initWithFrame:(CGRect)frame{ self = [super initWithFrame:frame]; if (self) { ....afert some code;[self createBUttonWithProperties]; }return self; },并将自定义view中的方法名称- (void)loadView更改为其他名称,如- (void)createBUttonWithProperties -
是的,这行得通(我称之为
-(void)setupSubviews),但它是“正确”的做法吗?我的意思是如果有像loadView这样的方法无论如何都会被调用,那么我更愿意使用它。
标签: objective-c ios7 uiviewcontroller subviews programmatically-created