delegate用法

13 篇文章 0 订阅
12 篇文章 0 订阅
创建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;
    
    
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值