zoukankan      html  css  js  c++  java
  • iOS 简单代理(delegate)实现

    昨天做了一个demo,用到了简单代理。

    delegate是ios编程的一种设计模式。我们可以用这个设计模式来让单继承的objective-c类表现出它父类之外类的特征。昨天这个代理实现如下:

    类GifView是继承自UIView的,它加载在RootViewController上来通过一个Timer播放动画。同时,RootViewController需要知道Timer的每次执行。

    代码如下。

    首先,定义GifView,在其头文件中定义代理EveryFrameDelegate,同时声明方法- (void)DoSomethingEveryFrame;

    #import <UIKit/UIKit.h>

    @protocol EveryFrameDelegate <NSObject>

    - (void)DoSomethingEveryFrame;

    @end

    @interface GifView : UIView
    {
    NSTimer *timer;
    id <EveryFrameDelegate> delegate;
    NSInteger currentIndex;
    }

    @property (nonatomic, assign) id <EveryFrameDelegate> delegate;

    @end

    然后,只要在GifView.m中让Timer在每次执行的时候调用delegate来执行DoSomethingEveryFrame,代码如下

    - (id)initWithFrame:(CGRect)frame
    {

    self = [super initWithFrame:frame];
    if (self)
    {
    timer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(play) userInfo:nil repeats:YES];
    [timer fire];
    }
    return self;
    }

    -(void)play
    {
    [delegate DoSomethingEveryFrame];

    }

    GifView上的工作就完成了。

    下面是RootViewController中的代码,RootViewController只要在定义GifView的时候指定其代理为自身,就可以知道Timer的每次执行:

    - (void)viewDidLoad
    {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    CGRect rect = CGRectMake(0, 0, 200, 200);
    GifView *tmp = [[GifView alloc] initWithFrame:rect];
    tmp.delegate = self;
    [self.view addSubview:tmp];
    [tmp release];
    }

    - (void)DoSomethingEveryFrame
    {
    NSLog(@"I'm the delegate! I'm doing printing!");
    }

    GifView中Timer每次执行都会打印一行

    I'm the delegate! I'm doing printing!

    故,RootViewController就知道Timer的每次执行了。

    ====================我是欢乐的分割线====================


    以下内容为2013.3.12添加

    在RootViewController的头文件中需要引入GifView.h这个头文件,并表明RootViewController遵循代理EveryFrameDelegate。否则会有警告出现。

    代码如下:

    #include <UIKit/UIKit.h>
    #import "GifView.h"
    
    @interface RootViewController : UIViewController <EveryFrameDelegate>
    
    @end

    另外,在定义代理的时候加上关键字@optional则表明这个代理可以不用实现所有的代理方法而不被报警告。

    代码如下:

    @protocol EveryFrameDelegate <NSObject>
    @optional
    
    - (void)ifYouNeedThis;
    - (void)DoSomethingEveryFrame;
    
    @end



  • 相关阅读:
    android界面基本属性
    iOS请求webservice
    图片在鼠标经过时变大
    控制字体大小,em与px的区别与应用
    IE的另类CSS hack,条件注释
    几种流行的AJAX框架jQuery,Mootools,Dojo,Ext JS的对比
    CSS实现文字压在边线上的效果,fieldset与legend
    每个.NET 开发人员应该下载的十个必备工具
    css做出丰富的Tooltips
    .NET牛人应该知道些什么?
  • 原文地址:https://www.cnblogs.com/lovekarri/p/2379197.html
Copyright © 2011-2022 走看看