1 #import "ViewController.h" 2 3 @interface ViewController () 4 5 @property (strong, nonatomic) UIButton *btn; 6 7 @end 8 9 @implementation ViewController 10 11 - (void)viewDidLoad { 12 [super viewDidLoad]; 13 14 //初始化按鈕,設置按鈕類型 15 self.btn = [UIButton buttonWithType:UIButtonTypeSystem]; 16 /* 17 Type: 18 UIButtonTypeCustom = 0, // 自定義類型 19 UIButtonTypeSystem NS_ENUM_AVAILABLE_IOS(7_0), // 系統類型 20 UIButtonTypeDetailDisclosure,//詳細描述樣式,圓圈中間加個i 21 UIButtonTypeInfoLight, //淺色的詳細描述樣式 22 UIButtonTypeInfoDark,//深色的詳細描述樣式 23 UIButtonTypeContactAdd,//加號樣式 24 UIButtonTypeRoundedRect = UIButtonTypeSystem, // 圓角矩形 25 */ 26 27 //設置按鈕位置和尺寸 28 self.btn.frame = CGRectMake(50, 50, 300, 50); 29 30 //設置按鈕文字標題 31 [self.btn setTitle:@"我是一個按鈕" forState:UIControlStateNormal]; 32 /* 33 State:前三個較為常用 34 UIControlStateNormal //正常狀態下 35 UIControlStateHighlighted //高亮狀態下,按鈕按下還未抬起的時候 36 UIControlStateDisabled //按鈕禁用狀態下,不能使用 37 UIControlStateSelected //選中狀態下 38 UIControlStateApplication //當應用程序標志時 39 UIControlStateReserved //為內部框架預留 40 */ 41 42 //設置按鈕文字顏色 43 [self.btn setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal]; 44 45 //設置背景圖片(需要注意按鈕類型最好為自定義,系統類型的會使圖片變暗) 46 // [self.btn setImage:[UIImage imageNamed:@"tupian"] forState:UIControlStateNormal]; 47 48 //設置按鈕文字大小 49 self.btn.titleLabel.font = [UIFont systemFontOfSize:20]; 50 51 //設按鈕背景顏色 52 self.btn.backgroundColor = [UIColor cyanColor]; 53 54 //設置按鈕文字陰影顏色 55 [self.btn setTitleShadowColor:[UIColor yellowColor] forState:UIControlStateNormal]; 56 57 //默認情況下,在按鈕被禁用時,圖像會被畫的顏色深一些。要禁用此功能,可以將這個屬性設置為NO 58 self.btn.adjustsImageWhenHighlighted = NO; 59 60 //默認情況下,按鈕在被禁用時,圖像會被畫的顏色淡一些。要禁用此功能,可以將這個屬性設置為NO 61 self.btn.adjustsImageWhenDisabled = NO; 62 63 //下面的這個屬性設置為yes的狀態下,按鈕按下會發光,這可以用於信息按鈕或者有些重要的按鈕 64 self.btn.showsTouchWhenHighlighted = YES; 65 66 //按鈕響應點擊事件,最常用的方法:第一個參數是目標對象,一般都是self; 第二個參數是一個SEL類型的方法;第三個參數是按鈕點擊事件 67 [self.btn addTarget:self action:@selector(Method) forControlEvents:UIControlEventTouchUpInside]; 68 69 //將控件添加到當前視圖上 70 [self.view addSubview:self.btn]; 71 72 } 73 74 - (void)Method 75 { 76 NSLog(@"學東哥哥隨筆~~~~"); 77 } 78 79 80 /*如果自定義按鈕類,可以重寫下面方法,定制自己需要的按鈕 81 82 - (CGRect)backgroundRectForBounds:(CGRect)bounds; //指定背景邊界 83 - (CGRect)contentRectForBounds:(CGRect)bounds; //指定內容邊界 84 - (CGRect)titleRectForContentRect:(CGRect)contentRect; //指定文字標題邊界 85 - (CGRect)imageRectForContentRect:(CGRect)contentRect; //指定按鈕圖像邊界 86 87 */ 88 89 90 91 - (void)didReceiveMemoryWarning { 92 [super didReceiveMemoryWarning]; 93 // Dispose of any resources that can be recreated. 94 } 95 96 @end