UIButton

按钮UIButton在app的出镜率也相当⾼。作⽤是响应⽤户点击的控件。    
创建UIButton,遵循⼀下⼏个步骤:   
1、⼀般⽤便利构造器来创建⼀个button对象。      
2、设置按钮的属性     
3、为按钮添加点击事件    
4、把按钮添加到⽗视图,得以显⽰     
//
//  ViewController.m
//  UIButton01
//
//  Created by cqy on 16/2/13.
//  Copyright © 2016年 程清杨. All rights reserved.
//

#import "ViewController.h"

@interface ViewController (){
    UIButton *button;
    UIButton *btn;
}

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
  
    //创建UIButton
    button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(20, 20, 80, 45);
    button.backgroundColor = [UIColor greenColor];
    //设置button的字体
    [button setTitle:@"按钮1" forState:UIControlStateNormal];
   //[button setTitle:@"按钮1" forState:UIControlStateHighlighted];
    //[button setTitle:@"按钮1" forState:UIControlStateSelected];
    //设置图必须使⽤镂空图⽚
    [button setImage:[UIImage imageNamed:@"key"] forState:UIControlStateNormal];
    //设置背景图⽚(不⽤镂空的)⽤来代替按钮
    [button setBackgroundImage:[UIImage imageNamed:@"open"] forState:UIControlStateNormal];
    //添加点击事件
    [button addTarget:self action:@selector(Open:) forControlEvents:UIControlEventTouchUpInside];
    /*
    第⼀个参数:指定谁来执⾏这个事件。
    第⼆个参数:指定谁来实现事件的⽅法,⽤@selector来寻找该类下的⽅法。
    第三个参数:触发方式
     */
    //removeTarget:acon:forControlEvents:移除监听
    [self.view addSubview:button];
    btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(120, 20, 80, 45);
    btn.backgroundColor = [UIColor redColor];
    [btn setTitle:@"按钮2" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(Delte) forControlEvents:UIControlEventTouchUpInside];
   
    [self.view addSubview:btn];
  
   
   
    // Do any additional setup after loading the view, typically from a nib.
}
-(void)Open:(UIButton *)open{
      self.view.backgroundColor = [UIColor redColor];
     NSLog(@"open.....");
}
-(void)Delte{
     self.view.backgroundColor = [UIColor whiteColor];
   
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
注释:1、self指的是指定本类实现这个点击事件
2、buttonAction来实现点击事件来做的事
 
 
原文地址:https://www.cnblogs.com/iQingYang/p/5193180.html