iOS UI04_Target-Action

//
//  MyButton.h
//  UI04_Target-Action
//
//  Created by dllo on 15/8/3.
//  Copyright (c) 2015年 zhozhicheng. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface MyButton : UIView
//通過MyButton實現button的點擊效果
//1.通過自定義的方法,把目標和動作傳到類的內部
-(void)addTarget:(id)target Action:(SEL)action;
//target:目標,button執行哪一個類的方法,對應的目標就是那個類的對象
//action:動作,讓button具體做什麼事,執行的方法就是對應的動作
//2.通過兩條屬性,把對應的目標和動作保存起來
@property(nonatomic,assign)id target;
@property(nonatomic,assign)SEL action;

@end
//
//  MyButton.m
//  UI04_Target-Action
//
//  Created by dllo on 15/8/3.
//  Copyright (c) 2015年 zhozhicheng. All rights reserved.
//

#import "MyButton.h"

@implementation MyButton

-(void)addTarget:(id)target Action:(SEL)action{
    //3.實現對應的自定義方法,並且讓兩個屬性來保存對應的目標和動作
    self.action=action;
    self.target=target;

}
//4.給Button一個觸發的條件,重寫觸摸方法,只要一觸碰touchBegan方法,就會讓button執行相應點擊方法
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    //5.類把他的方法交給MyButton來完成
    [self.target performSelector:self.action withObject:self];
}


@end
//
//  MainViewController.m
//  UI04_Target-Action
//
//  Created by dllo on 15/8/3.
//  Copyright (c) 2015年 zhozhicheng. All rights reserved.
//

#import "MainViewController.h"
#import "MyButton.h"
@interface MainViewController ()

@end

@implementation MainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    // 通過UIView來模擬一個Button點擊

    MyButton *myButton=[[MyButton alloc] initWithFrame:CGRectMake(100, 100, 150, 40)];
    myButton.backgroundColor=[UIColor yellowColor];
    myButton.layer.borderWidth=1;
    myButton.layer.cornerRadius=10;
    [self.view addSubview:myButton];
    [myButton release];

    //6.使用自定義的方法
    [myButton addTarget:self Action:@selector(click:)];


}
-(void)click:(UIButton *)button
{
    NSLog(@"實現點擊效果");
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章