UISB Button 事件

viewController.m

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController



-(void) createBtn
{
    UIButton* btn=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    btn.frame=CGRectMake(100, 100, 100, 40);
    
    [btn setTitle:@"按钮" forState:UIControlStateNormal];
    
    btn.backgroundColor=[UIColor redColor];
    
    
    //向按钮添加事件函数
    //P1 :谁来实现事件函数
    //P2: @select (pressBtn):函数对象 ,当按钮满足P3事件类型时,调用函数 若穿参 则+ :
    //P3 :UIControlEventTouchUpInside 事件处理函数类型
    
    
    [btn addTarget:self action:@selector(pressBtn:) forControlEvents:UIControlEventTouchUpInside];

    
    [btn addTarget:self action:@selector(touchdown) forControlEvents:UIControlEventTouchDown];
    
    [self.view addSubview:btn];
    
    
    
    UIButton* btn2 =[UIButton buttonWithType:UIButtonTypeRoundedRect];
    btn2.frame=CGRectMake(100, 200, 80, 40);
    [btn2 setTitle:@"按钮02" forState:UIControlStateNormal];
    [btn2 addTarget:self action:@selector(pressBtn:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:btn2];
    
    //设置按钮标记
    btn.tag=101;
    btn2.tag=102;
    
}

-(void) touchdown
{
    NSLog(@"按钮被触碰");
    
}

//参数为调用此函数按钮对象本身
-(void) pressBtn:(UIButton*)btn
{
    if(btn.tag==101)
    {
        NSLog(@"按钮1");
    }
    if (btn.tag==102)
    {
        NSLog(@"按钮2");
        
    }
    
}

//-(void)pressBtn
//{
//
//    NSLog(@"点击按钮");
//}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self createBtn];
}


@end
原文地址:https://www.cnblogs.com/zhangqing979797/p/13629766.html