创建TouchView类
@class TouchView;
@protocol TouchViewDelegate <NSObject>
@optional
-(void)changeColor:(TouchView *)sender ;//变颜色方法
-(void)changePosition:(TouchView *)sender touches:(NSSet*)touches;//改变位置方法
@end
@interface TouchView : UIView
@property(nonatomic,assign)id<TouchViewDelegate>delegate;//定于属性
-(id)initWithFrame:(CGRect)frame delegate:(id)delegate;//初始化
@end
实现
#import "TouchView.h"
@implementation TouchView
//初始化
- (id)initWithFrame:(CGRect)frame delegate:(id)delegate
{
self = [super initWithFrame:frame];
if (self) {
_delegate=delegate;
// Initialization code
}
return self;
}
//判断是否实现协议方法
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
if ([_delegate respondsToSelector:@selector(changeColor:)]) {
[_delegate changeColor:self];
}
if([_delegate respondsToSelector:@selector(changePosition:touches:)])
{
[_delegate changePosition:self touches:touches];
}
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
[_delegate changePosition:self touches:touches];
}
root.h文件
#import "TouchView.h"
@interface RootViewController : UIViewController<TouchViewDelegate> //接受代理
@end
实现文件
- (void)viewDidLoad
{
[super viewDidLoad];
TouchView *touchView=[[TouchView alloc]initWithFrame:CGRectMake(100, 150, 200, 50) delegate:self];
touchView.backgroundColor=[UIColor redColor];
[self.view addSubview:touchView];
// Do any additional setup after loading the view.
}
-(void)changeColor:(TouchView *)touch
{
touch.backgroundColor=[UIColor orangeColor];
}
-(void)changePosition:(TouchView *)touch touches:(NSSet*)touches
{
UITouch *touvhView=[touches anyObject];
CGPoint point=[touvhView locationInView:self.view.window];
CGPoint newPoint=[touvhView previousLocationInView:self.view.window];
CGFloat x=point.x-newPoint.x;
CGFloat y=point.y-newPoint.y;
CGRect bounds=self.view.bounds;
CGRect newbounds=CGRectMake(bounds.origin.x-x, bounds.origin.y-y, bounds.size.width, bounds.size.height);
self.view.bounds=newbounds;
}