刚刚在Xcode中创建了一个新项目(基于视图),并尝试以编程方式创建这样的按钮,但它没有显示。为什么不呢?
- (void)applicationDidFinishLaunching:(UIApplication *)application {
// Override point for customization after app launch
[window addSubview:viewController.view];
CGRect rect = CGRectMake(0, 20,100,20);
UIButton *button = [[UIButton alloc] initWithFrame:rect];
[viewController.view addSubview:button];
[window makeKeyAndVisible];
}
答案 0 :(得分:2)
最好不要使用应用程序委托来设置视图,只需加载第一个根视图。因此,将appDelegate的applicationDidFinishLaunching更改回
- (void)applicationDidFinishLaunching:(UIApplication *)application {
// Override point for customization after app launch
[window addSubview:viewController.view];
[window makeKeyAndVisible];
}
进入您的视图,它会调用并打入此代码,这将为您创建您的UIButton。我还添加了背景颜色的更改,以确保您正在加载此视图。
- (void)loadView {
self.view = [[UIView alloc] initWithFrame:CGRectMake(0,0,320,480)];
self.view.backgroundColor = [UIColor redColor];
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 20, 100, 20)];
[button setTitle:@"UIButton!" forState:UIControlStateNormal];
[button setReversesTitleShadowWhenHighlighted:YES];
[button setShowsTouchWhenHighlighted:YES];
[self.view addSubview:button];
[button release];
}
通常我更喜欢以编程方式构建我的视图,因为我可以覆盖drawRect:在InterfaceBuilder afaik中你无法做到。
答案 1 :(得分:1)
尝试使用[UIButton buttonWithType: UIButtonTypeCustom]
或[UIButton buttonWithType: UIButtonTypeRoundedRect]
我觉得那些工作好多了。他们肯定更加自我记录。
答案 2 :(得分:0)
你确定没有显示吗?它可能只是透明而你无法看到它,尝试将按钮背景颜色设置为某种东西......
答案 3 :(得分:-5)
不要那样做。使用Interface Builder。