码迷,mamicode.com
首页 > 移动开发 > 详细

iOS UI04_Target-Action

时间:2015-08-04 23:08:02      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:ios   target-act   ui   

//
//  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

版权声明:本文为博主原创文章,未经博主允许不得转载。

iOS UI04_Target-Action

标签:ios   target-act   ui   

原文地址:http://blog.csdn.net/cheng_xiansheng/article/details/47282625

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!