UI之targetAction

本文介绍了一种通过targetAction机制实现视图交互的方法,包括如何响应触摸事件以改变视图的颜色和大小。通过创建自定义视图MangoView,并在MainViewController中设置不同的响应动作,实现了点击视图后的动态效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

用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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值