标签:
拖拽添加一个Button Type 为custom,分别设置State config分别为Default, highlighted, selected.并分别选择Background为image全称。
1 #import <UIKit/UIKit.h> 2 3 @interface ViewController : UIViewController 4 5 @property (nonatomic, strong) IBOutlet UIButton *btn; 6 7 @end 8 9 .m文件中 10 - (IBAction)btnSelected:(id)sender 11 { 12 UIButton *btn = (UIButton *)sender; 13 btn.selected = YES; 14 } 15 16 完成操作
二、手写代码法
1 //宏定义文件 2 #ifndef Globaldefine_h 3 #define Globaldefine_h 4 5 #define SCREENWIDTH [[UIScreen mainScreen] bounds].size.width 6 #define SCREENHEIGHT [[UIScreen mainScreen] bounds].size.height 7 8 #endif /* Globaldefine_h */ 9 10 11 //视图控制器.h文件 12 #import <UIKit/UIKit.h> 13 14 @interface ViewController : UIViewController 15 16 @property (nonatomic, strong) IBOutlet UIButton *btn; 17 18 @end 19 20 #import "ViewController.h" 21 #import "Globaldefine.h" 22 23 @interface ViewController () 24 25 @end 26 27 @implementation ViewController 28 29 - (void)viewDidLoad 30 { 31 [super viewDidLoad]; 32 _btn = [UIButton buttonWithType:UIButtonTypeCustom];//按钮状态 33 _btn.frame = CGRectMake(SCREENWIDTH / 2 - 30, SCREENHEIGHT / 2 - 30, 60, 60);//设置按钮位置和大小 34 [_btn setBackgroundImage:[UIImage imageNamed:@"xmh.png"] forState:UIControlStateNormal]; 35 [_btn setBackgroundImage:[UIImage imageNamed:@"wdh.png"] forState:UIControlStateHighlighted]; 36 [_btn setBackgroundImage:[UIImage imageNamed:@"syh.png"] forState:UIControlStateSelected]; 37 [self.view addSubview:_btn]; 38 39 40 [_btn addTarget:self action:@selector(btnSelected:) forControlEvents:UIControlEventTouchUpInside];//@selector(btnSelected:)冒号就是把_btn传过去 41 } 42 - (void)btnSelected:(UIButton *)btn 43 { 44 if (btn.selected) 45 { 46 btn.selected = NO; 47 } 48 else 49 { 50 btn.selected = YES; 51 } 52 } 53 54 - (void)didReceiveMemoryWarning { 55 [super didReceiveMemoryWarning]; 56 // Dispose of any resources that can be recreated. 57 } 58 59 @end
标签:
原文地址:http://www.cnblogs.com/songlei0601/p/5766658.html