您的位置:首页 > 产品设计 > UI/UE

UI之targetAction

2015-12-14 10:16 429 查看
用targetAction来改变view的大小和颜色

#import <UIKit/UIKit.h>

@interface MangoView : UIView

//向外部公开接口,传入目标和动作

- (void)addtarget:(id)target action:(SEL)action;

@end

#import "MangoView.h"

#import "MainViewController.h"

@interface MangoView ()

{

//target、action的属性命名方法:

id _target;//目标,将要执行动作的对象

SEL _action;//动作,目标对象将要执行的操作

}

@end

@implementation MangoView

- (instancetype)initWithFrame:(CGRect)frame

{

self = [super initWithFrame:frame];

if (self) {

[self lodingCustomView];

}

return self;

}

- (void)lodingCustomView{

}

- (void)addtarget:(id)target action:(SEL)action{

// 把外部传入的target目标和action动作赋值给mangoView自身的目标和动作的实例变量

_target = target;

_action = action;

}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

// 当点击之后我们需要让目标去执行对应的动作

[_target performSelector:_action];

}

@end

#import "MainViewController.h"

#import "MangoView.h"

@interface MainViewController ()

@property(nonatomic,retain)MangoView *mangoView;

@property(nonatomic,retain)MangoView *mangoView1;

@end

@implementation MainViewController

- (void)viewDidLoad {

[super viewDidLoad];

// Do any additional setup after loading the view.

self.view.backgroundColor = [UIColor cyanColor];

self.mangoView = [[MangoView alloc]initWithFrame:CGRectMake(40, 100, 300, 100)];

self.mangoView.backgroundColor = [UIColor yellowColor];

//在实例对象中添加target和action方法

[self.mangoView addtarget:self action:@selector(changeColor)];

[self.view addSubview:self.mangoView];

[self.mangoView release];

self.mangoView1 = [[MangoView alloc]initWithFrame:CGRectMake(40, 270, 300, 150)];

self.mangoView1.backgroundColor = [UIColor greenColor];

[self.mangoView1 addtarget:self action:@selector(changeSize)];

[self.view addSubview:self.mangoView1];

[self.mangoView1 release];

}

- (void)changeColor{

self.mangoView.backgroundColor = [UIColor orangeColor];

}

- (void)changeSize{

self.mangoView1.frame = CGRectMake(40, 270, 300, 100);

}

- (void)didReceiveMemoryWarning {

[super didReceiveMemoryWarning];

// Dispose of any resources that can be recreated.

}

@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: