1. 什么是按鈕
2. 按鈕的基本使用
知識點詳解
1. 什么是按鈕?
如下如所示, 我們很多時候需要在讓用戶控制我們的應用, 一般可以使用按鈕

2. 按鈕的使用
//按鈕類UIButton的使用 //1.如何創建一個按鈕 //創建按鈕 UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem]; //設置位置 button.frame = CGRectMake(100, 100, 100, 30); //設置文本 [button setTitle:@"點我啊" forState:UIControlStateNormal]; [self.window addSubview:button]; //說明1: 按鈕一般使用buttonWithType這個類方法創建, 參數為按鈕的類型 // 最常常用的有如下兩種類型 // <2>UIButtonTypeCustom 圖片按鈕 // <1>UIButtonTypeSystem 系統按鈕 //說明2: 設置顯示的文本時候參數2為狀態 // 常用的是 UIControlStateNormal表示正常狀態 //說明3: // ios6: 默認就是圓角矩形按鈕 // ios7: 所有按鈕沒有邊框了(扁平化) //告訴按鈕: 被點了應該執行那個方法 // forControlEvents 控件事件類型 // 常用事件: 按下彈起 // addTarget和action表示由那個方法去處理這個事件 [button addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside]; //2.設置文本顏色 [button setTitleColor:[UIColor greenColor] forState:UIControlStateNormal]; //3.設置字體 button.titleLabel.font = [UIFont systemFontOfSize:24]; //4.禁用按鈕(NO表示禁止) button.enabled = YES; //5.被點擊時的高亮效果 button.showsTouchWhenHighlighted = YES; //6.設置Tag值 // 每個控件都有tag這個屬性 // 給這個屬性賦任意的值,區分不同的控件 // 10個按鈕的事件處理方法都是一個 button.tag = 100; //7.實現帶圖片的按鈕 UIButton *imageButton= [UIButton buttonWithType:UIButtonTypeCustom]; imageButton.frame = CGRectMake(100, 200, 100, 30); //注意: 使用的圖片資源拷入工程即可 UIImage *image = [UIImage imageNamed:@"back.png"]; //按鈕添加背景圖片 [imageButton setBackgroundImage:image forState:UIControlStateNormal]; //設置文本左邊的圖片 [imageButton setImage:[UIImage imageNamed:@"logo.png"] forState:UIControlStateNormal]; //8.設置按鈕中圖片和文本的偏移(位置) // UIEdgeInsets //top, left, bottom, right //可以控制圖片和文本與按鈕上邊,左邊,底邊和右邊的距離 imageButton.imageEdgeInsets = UIEdgeInsetsMake(0, 60, 0, 0); imageButton.titleEdgeInsets = UIEdgeInsetsMake(0, -60, 0, 0); [self.window addSubview:imageButton]; [imageButton addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside]; [imageButton setTitle:@"點我呀" forState:UIControlStateNormal]; self.window.backgroundColor = [UIColor grayColor]; [self.window makeKeyAndVisible]; return YES;}//為了按鈕添加一個點擊事件的處理方法//參數: 是固定的, 參數就是事件的來源-(void)btnClick//-(void)btnClick:(UIButton *)button{ //NSLog(@"我被點了....."); //彈出一個對話框 UIAlertView *alertView = [[UIAlertView alloc] init]; alertView.message = @"按鈕被點了"; [alertView addButtonWithTitle:@"取消"]; [alertView show];}
新聞熱點
疑難解答