如何在不使用Interface builder的情况下创建一个简单的按钮?
你需要像这样声明一个UIButton:
UIButton *newButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 80, 40)];
[newButton setTitle:@"Some Button" forState:UIControlStateNormal];
然后将按钮添加到视图中-
[self.view addSubview: newButton]; // (could be another view other then self.view)
最后,如果你想在按下按钮时发生一些动作,你可以添加:
[newButton addTarget:self action:@selector(doSomething)
forControlEvents:UIControlEventTouchUpInside];
并声明函数:
- (void) doSomething
{
NSLog(@"Button pressed");
}
当然别忘了松开按钮
试试
UIButton *playButton = [[UIButton buttonWithType:UIButtonTypeRoundedRect];
playButton.frame = CGRectMake(110.0, 360.0, 100.0, 30.0);
[playButton setTitle:@"Play" forState:UIControlStateNormal];
playButton.backgroundColor = [UIColor clearColor];
[playButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal ];
UIImage *buttonImageNormal = [UIImage imageNamed:@"blueButton.png"];
UIImage *strechableButtonImageNormal = [buttonImageNormal stretchableImageWithLeftCapWidth:12 topCapHeight:0];
[playButton setBackgroundImage:strechableButtonImageNormal forState:UIControlStateNormal];
UIImage *buttonImagePressed = [UIImage imageNamed:@"whiteButton.png"];
UIImage *strechableButtonImagePressed = [buttonImagePressed stretchableImageWithLeftCapWidth:12 topCapHeight:0];
[playButton setBackgroundImage:strechableButtonImagePressed forState:UIControlStateHighlighted];
[playButton addTarget:self action:@selector(playAction:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:playButton];
像这样-
自定义按钮-
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 100.0f, 30.0f)];
系统按钮-
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];