尝试使用2个UIButton创建视图时出错

时间:2011-04-15 20:18:51

标签: objective-c cocoa-touch ios uibutton

我正在尝试使用两个UIButton创建一个视图。代码编译时没有任何错误,但按钮没有任何标签,也无法单击它们。 enter image description here

-(id)initWithTabBar {

if ([self init]) {
    self.title = @"Tab1";
    self.tabBarItem.image = [UIImage imageNamed:@"promoters.png"];
    self.navigationItem.title = @"Nav 1";
}

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button setTitle:@"Button" forState:UIControlStateNormal];
[button addTarget:self action:@selector(facebookAuthorize) forControlEvents:UIControlEventTouchDown];
[button setFrame:CGRectMake(10, 10, 100, 100)];

[self.view addSubview:button];

[button release];

UIButton *button2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button2 setTitle:@"Button" forState:UIControlStateNormal];
[button2 addTarget:self action:@selector(facebookLogin) forControlEvents:UIControlEventTouchDown];
[button2 setFrame:CGRectMake(110, 10, 100, 100)];

[self.view addSubview:button2];

[button2 release];

return self;
}

2 个答案:

答案 0 :(得分:1)

不要释放这些按钮。它们被创建为自动释放的对象。如documentation

中所述
  

您只能发布或自动发布   你拥有的物品。你取得了所有权   如果使用a创建对象   名称以“alloc”开头的方法,   “新”,“复制”或“mutableCopy”

这些单词都不会出现在 buttonWithType:中,因此您不承担任何责任,并且可以安全地假设它已自动释放。

答案 1 :(得分:0)

如前所述,按钮在withType时无法命名。使单词出现在uibutton中的代码是:

  UIButton *someButton=[[[UIButton alloc]initWithFrame:CGRectMake(140, 6, 175, 36)]autorelease];
[someButton addTarget:self action:@selector(facebookLogin) forControlEvents:UIControlEventTouchDown];
[someButton setTitle:@"Button" forState:UIControlStateNormal];
[self.view addSubview:someButton];