自定义target - action 方法
HomeViewController.m
#import "HomeViewController.h"
#import "TouchViewPro.h"
@interface HomeViewController (){
TouchViewPro *touchViewPro;
}
@end
@implementation HomeViewController
- (void)viewDidLoad {
[super viewDidLoad];
touchViewPro = [[TouchViewPro alloc] initWithFrame:CGRectMake(65, 65, 100, 100)];
touchViewPro.backgroundColor = [UIColor blackColor];
[self.view addSubview:touchViewPro];
[touchViewPro addTarget:self action:@selector(change)];
[touchViewPro release];
}
- (void)change {
touchViewPro.frame = CGRectMake(arc4random() % (325 - 50 + 1) + 50, arc4random() % (325 - 50 + 1) + 50, arc4random() % 51, arc4random() % 70);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
-----------------------------------------------<TouchViewPro.h>-----------------------------------
#import <UIKit/UIKit.h>
@interface TouchViewPro : UIView
- (void)addTarget:(id)target action:(SEL)action;
@end
--------------------------------------------------<TouchViewPro.m>-------------------------------------------------
#import "TouchViewPro.h"
@interface TouchViewPro(){
id _target;
SEL _action;
}
@end
@implementation TouchViewPro
- (void)addTarget:(id)target action:(SEL)action {
_action = action;
_target = target;
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
[_target performSelector:_action withObject:self];
// self.frame = CGRectMake(arc4random() % (325 - 50 + 1) + 50, arc4random() % (325 - 50 + 1) + 50, arc4random() % 51, arc4random() % 70);
}
@end
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步