IOS-UIButton使用

1788 ワード

一、IOS UIButtonの基本属性
//     Button  ,       button
//     button:UIButtonTypeRoundedRect
//         buttonWithType:    +    ,    alloc init    
UIButton* button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(100, 100, 100, 40);

//        
[button setTitle:@"  " forState:UIControlStateNormal];

//        
[button setTitle:@"  " forState:UIControlStateHighlighted];

//         
button.backgroundColor = [UIColor redColor];

//               ,        ,            
[button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];

//            
[button setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];

//          ,  titleColor          
[button setTintColor:[UIColor whiteColor]];

// titleLabel:UILabel  
button.titleLabel.font = [UIFont systemFontOfSize:25];
以上、UIButtonの基本プロパティの使用について説明します.
二、カスタム画像付きUIButton
UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(100, 200, 100, 100);
UIImage* icon1 = [UIImage imageNamed:@"img1"];
UIImage* icon2 = [UIImage imageNamed:@"img2"];
[button setImage:icon1 forState:UIControlStateNormal];
[button setImage:icon2 forState:UIControlStateHighlighted];
実は簡単ですが、2つの画像クラスを作成しbuttonに設定します.
三、UIButtonにクリックイベントを追加する
[button addTarget:self action:@selector(clickButton:) forControlEvents:UIControlEventTouchUpInside];
    
button.tag = 110;

//         

//               
-(void) clickButton:(UIButton*) btn {
    if (btn.tag == 100) {
        NSLog(@"     ");
    }
}
トリガ関数の追加も簡単であり,各UIButtonには設定可能なtagがあり,このtagにより,複数のUIButtonが同じトリガ関数を共有する場合を区別できる.
それ自体がパラメータ伝達されていない場合は、clickButtonの後ろにある:削除して、対応するトリガ関数パラメータの個数を変更すればいいです.