0
我正在嘗試編程創建的UI的清潔實現。以編程方式清潔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;
}
而定製UIView
在MenuView.m
實現以下
- (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方法中的NSLog
會觸發並顯示320 x 548的幀大小,但loadView方法不會被調用。 我在做什麼錯?
感謝
我想'loadView'呼籲'UIViewController'子類類不能爲自定義'UIView' – 2014-09-03 11:14:12
OK,我在哪裏設置一個視圖的子視圖? – Joseph 2014-09-03 11:15:29
嘗試在初始化過程中調用此按鈕創建方法,例如' - (id)initWithFrame:(CGRect)frame {self = [super initWithFrame:frame]; (self){.... afert一些代碼; [self createBUttonWithProperties]; }返回自我; }'並將自定義'view'中的方法名稱' - (void)loadView'更改爲其他名稱,如' - (void)createBUttonWithProperties' – 2014-09-03 11:17:59