0

刚刚在 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];
}
4

4 回答 4

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 中做到这一点。

于 2009-08-17T15:06:43.593 回答
1

尝试使用[UIButton buttonWithType: UIButtonTypeCustom]或创建您的按钮[UIButton buttonWithType: UIButtonTypeRoundedRect]

我发现这些工作好多了。他们当然更自我记录。

于 2009-08-17T15:55:58.720 回答
0

你确定它不显示?它可能只是透明的,你看不到它,尝试将按钮背景颜色设置为某种东西......

于 2009-08-17T14:21:24.647 回答
-5

不要那样做。使用界面生成器。

于 2009-08-17T14:20:48.190 回答