码迷,mamicode.com
首页 > 其他好文 > 详细

delegate的练习

时间:2015-10-31 21:23:12      阅读:224      评论:0      收藏:0      [点我收藏+]

标签:

//在RootViewController.h里面遵守协议

#import <UIKit/UIKit.h>

 

@interface RootViewController : UIViewController

 

@end

 -----------------------------------<>-------------------------

//RootViewController.m

#import "RootViewController.h"

#import "TouchView.h"

 

@interface RootViewController ()<TouchViewDelegate>{

    TouchView *touch;

}

 

@end

 

@implementation RootViewController

 

- (void)viewDidLoad {

    [super viewDidLoad];

    touch = [[TouchView alloc] initWithFrame:CGRectMake(10, 65, 100, 100)];

    touch.backgroundColor = [UIColor redColor];

    touch.delegate = self;

    [self.view addSubview:touch];

    [touch release];

}

 

- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

 

 

#pragma mark - TouchViewDelegate

-(void)canTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {

    touch.backgroundColor = [UIColor colorWithRed:arc4random() % 256 / 255. green:arc4random() % 256 / 255. blue:arc4random() % 256 / 255. alpha:1.0];

}

@end

 ----------------------------<自己定义的TouchView, 继承于UIView>-----------------------------

#import <UIKit/UIKit.h>

 

@protocol TouchViewDelegate <NSObject>//制订协议, 协议名 : 类名 + delegate

 

-(void)canTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;//制定协议里面的方法

 

@end

@interface TouchView : UIView

@property (nonatomic, retain) id<TouchViewDelegate>delegate;

@end

 ----------------------------------------------<>-------------------------------------------

#import "TouchView.h"

 

@implementation TouchView

 

 

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {

//让代理执行本应该TouchView完成的方法

    if ([_delegate respondsToSelector:@selector(canTouchesEnded:withEvent:)]) {

        [_delegate canTouchesEnded:touches withEvent:event];//把参数传进来

    }

    

    

//    self.backgroundColor = [UIColor colorWithRed:arc4random() % 256 / 255. green:arc4random() % 256 / 255. blue:arc4random() % 256 / 255. alpha:1.0];

}

@end

 

delegate的练习

标签:

原文地址:http://www.cnblogs.com/hsxblog/p/4926160.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!