delegate用法

創建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;
    
    
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章