UI: UIButton

- (void) buttonIsPressed:(UIButton *)paramSender{ 
NSLog(@"Button is pressed.");
}
- (void) buttonIsTapped:(UIButton *)paramSender{ 
NSLog(@"Button is tapped.");
}

- (void)viewDidLoad{
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; self.myButton.frame = CGRectMake(110.0f,200.0f,100.0f,37.0f);
[self.myButton setTitle:@"Press Me" forState:UIControlStateNormal];
[self.myButton setTitle:@"I'm Pressed" forState:UIControlStateHighlighted];
[self.myButton addTarget:self action:@selector(buttonIsPressed:) forControlEvents:UIControlEventTouchDown];
[self.myButton addTarget:self action:@selector(buttonIsTapped:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:self.myButton];
}
一个按钮也可以显示一个图片。图片将会替换按钮默认的外观。当你要给不同状态下按 钮定义不同的图片时,要确保你的按钮是属于 UIBttonTypeCustom 类型的。这里准备了两张 图片,一张是􏰀供给正常按钮状态下的,一张是􏰀供给高亮(按下)状态下的。现在创建一 个自定义按钮并绑定这两张图片。一张是正常状态下的,一张是高亮状态下的。如下所示。 
UIImage *normalImage = [UIImage imageNamed:@"NormalBlueButton.png"]; 
UIImage *highlightedImage = [UIImage imageNamed:@"HighlightedBlueButton"]; 
self.myButton = [UIButton buttonWithType:UIButtonTypeCustom]; 
self.myButton.frame = CGRectMake(110.0f,200.0f,100.0f,37.0f);
[self.myButton setBackgroundImage:normalImage forState:UIControlStateNormal];
[self.myButton setTitle:@"Normal" forState:UIControlStateNormal];
[self.myButton setBackgroundImage:highlightedImage forState:UIControlStateHighlighted];
[self.myButton setTitle:@"Pressed" forState:UIControlStateHighlighted];
我们使用 setBackgroundImage: forState:这个方法设置背景图片。有了背景图片,我们依然可以使用 setTitle:forSate:这 个方法在背景图上方显示文本。假如你的背景图片包含了文本,你就不必再给按钮设置标题 了,你可以使用 setImage:forState:这个方法或者简单的将按钮上的标题删除。 

 

 

posted @ 2014-10-14 09:40  safiri  阅读(183)  评论(0编辑  收藏  举报