头文件
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@property (nonatomic,strong) UIButton *myButton;
@end
实现
#import "ViewController.h"
@interfaceViewController ()
@end
@implementation ViewController
- (void) buttonIsPressed: (UIButton *) paramSender {
NSLog(@"Button is pressed.");
}
- (void) buttonIsTapped: (UIButton *) paramSender {
NSLog(@"Button is tapped.");
}
- (void)viewDidLoad
{
[superviewDidLoad];
UIImage *normalImage = [UIImage imageNamed:@"normalStateImage"];
UIImage *higthLightImage = [UIImage imageNamed:@"higthLightStateImage"];
self.myButton = [UIButtonbuttonWithType:UIButtonTypeCustom]; //必须在初始化时为UIButton设置一个type,想用图片时必须是这种type
self.myButton.frame = CGRectMake(120.0f, 200.0f, 200.0f, 200.0f);
[self.myButtonsetBackgroundImage:normalImage forState:UIControlStateNormal];
[self.myButtonsetTitle:@"pressed me"forState:UIControlStateNormal];
[self.myButtonsetBackgroundImage:higthLightImage forState:UIControlStateHighlighted];
[self.myButtonsetTitle:@"I'm pressed"forState:UIControlStateHighlighted];
[self.myButtonaddTarget:selfaction:@selector(buttonIsPressed:) forControlEvents:UIControlEventTouchDown];
[self.myButtonaddTarget:selfaction:@selector(buttonIsTapped:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:self.myButton];
}
- (void)didReceiveMemoryWarning
{
[superdidReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end