iOS开发 delegate,SEL和Block

iOS开发 delegate,SEL和Block


在Object-c中解决子类和父类之间事件传递,不同根类之间事件传递的三种方法
由于Object-c是单向继承的,父类 向子类传事件,数据,可用点语法,或者直接调用成员函数即可,
但是相反方向则需要引入委托,回调这样的概念
下面我将给出继承UIview,为他的子类添加点击事件,让他去改变父视图的背景色这个简单的例子的三种实现方法:


首先建立一个MyView 继承UIView

1.Delegate    编写协议

头文件  MyView.h

//

//  MyView.h

//  myView

//

//  Created by mac_shun on 13-9-7.

//  Copyright (c) 2013 wangshunPush. All rights reserved.

//


#import <UIKit/UIKit.h>


@protocol MyViewDelegate;


@interface MyView :UIView

{

   id <MyViewDelegate> _delegate;

}

@property (nonatomic,retainid <MyViewDelegate> delegate;


@end



@protocol MyViewDelegate <NSObject>


-(void)changeColor;


@end


协议中给出changeColor方法,让遵守该协议的类来实现这个方法
实现文件   MyView.m

//

//  MyView.m

//  myView

//

//  Created by mac_shun on 13-9-7.

//  Copyright (c) 2013 wangshunPush. All rights reserved.

//


#import "MyView.h"


@implementation MyView

@synthesize delegate =_delegate;


- (id)initWithFrame:(CGRect)frame

{

   self = [superinitWithFrame:frame];

   if (self) {

        // Initialization code

        

       //允许触发

        self.userInteractionEnabled =YES;

    }

    return self;

}


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

{

   if (self.delegate &&  [self.delegate respondsToSelector:@selector(changeColor)]) {

        //  delegate 去掉 自己实现的  changeColor 方法

        [self.delegate performSelector:@selector(changeColor)];

    }

}



/*

// Only override drawRect: if you perform custom drawing.

// An empty implementation adversely affects performance during animation.

- (void)drawRect:(CGRect)rect

{

    // Drawing code

}

*/


@end



头文件 ViewController.h
在控制器中实例化MyView

#import <UIKit/UIKit.h>

#import "MyView.h"


@interface ViewController :UIViewController<MyViewDelegate>


@end


下面是实现文件 ViewController.m

//

//  ViewController.m

//  myView

//

//  Created by mac_shun on 13-9-7.

//  Copyright (c) 2013 wangshunPush. All rights reserved.

//


#import "ViewController.h"


@interface ViewController ()


@end


@implementation ViewController


- (void)viewDidLoad

{

    [superviewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

    self.view.backgroundColor =[UIColorscrollViewTexturedBackgroundColor];

    

    MyView *v =[[MyViewalloc]initWithFrame:CGRectMake(0,0,100,100)];

    v.backgroundColor = [UIColorredColor];

    v.delegate =self;

    

    [self.viewaddSubview:v];

    

}


-(void)changeColor//协议方法

{

    self.view.backgroundColor = [UIColorunderPageBackgroundColor];

}


- (void)didReceiveMemoryWarning

{

    [superdidReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


@end


2.SEL    

还是Myview  加入SEL 变量
并加入一个 addTarget方法

头文件  MyView.h

#import <UIKit/UIKit.h>




@interface MyView :UIView

{

   id  delegate;

    

   SEL method;

}


-(void)addTarget:(id) d action:(SEL) m;


@end


实现文件   MyView.m

//

//  MyView.m

//  myView

//

//  Created by mac_shun on 13-9-7.

//  Copyright (c) 2013 wangshunPush. All rights reserved.

//


#import "MyView.h"


@implementation MyView


- (id)initWithFrame:(CGRect)frame

{

   self = [superinitWithFrame:frame];

   if (self) {

        // Initialization code

        

       //允许触发

        self.userInteractionEnabled =YES;


    }

    return self;

}


-(void)addTarget:(id)d action:(SEL)m

{

   delegate = d;

    

   method   = m;

    

}


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

{

    if (delegate && [delegaterespondsToSelector:method]) {

        //delegate  method 方法

        [delegateperformSelector:methodwithObject:self];

    }

    

}



/*

// Only override drawRect: if you perform custom drawing.

// An empty implementation adversely affects performance during animation.

- (void)drawRect:(CGRect)rect

{

    // Drawing code

}

*/


@end



下面ViewController.m

#import "ViewController.h"


@interface ViewController ()


@end


@implementation ViewController


- (void)viewDidLoad

{

    [superviewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

    self.view.backgroundColor =[UIColorscrollViewTexturedBackgroundColor];

    

    MyView *v =[[MyViewalloc]initWithFrame:CGRectMake(0,0,100,100)];

    v.backgroundColor = [UIColorredColor];

    

    [vaddTarget:selfaction:@selector(changeColorForSEL:)];

    

    [self.viewaddSubview:v];

    

}


-(void)changeColorForSEL:(MyView*)view

{

    self.view.backgroundColor = [UIColorunderPageBackgroundColor];

}


3.Block方法

函数指针

头文件  MyView.h

#import <UIKit/UIKit.h>


@interface MyView :UIView

{

    //定义一个指针变量 getMethod,这个指针指向一个函数

   void  (^getMethod)(MyView*);

    

}

/*

    MyView添加一个方法  

    

    形参      m

 

    形参类型  为一个函数的地址 void (^)(MyView*)

*/

-(void)addBlockMethod:(void (^)(MyView* view)) m;


@end



实现文件   MyView.m

#import "MyView.h"


@implementation MyView


- (id)initWithFrame:(CGRect)frame

{

   self = [superinitWithFrame:frame];

   if (self) {

        // Initialization code

        

       //允许触发

        self.userInteractionEnabled =YES;


    }

    return self;

}


-(void)addBlockMethod:(void (^)(MyView * view))m

{

    //获得外部函数的地址

    [getMethod release];

    

   getMethod = [mcopy];

    

}


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

{

    if (getMethod) {//当触发view调用已经指向的函数

       getMethod(self);

    }

}



@end



头文件   ViewController.h

#import <UIKit/UIKit.h>

#import "MyView.h"


@interface ViewController :UIViewController


@end


实现文件   ViewController.m

#import "ViewController.h"


@interface ViewController ()


@end


@implementation ViewController


- (void)viewDidLoad

{

    [superviewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

    self.view.backgroundColor =[UIColorscrollViewTexturedBackgroundColor];

    

    MyView *v =[[MyViewalloc]initWithFrame:CGRectMake(0,0,100,100)];

    v.backgroundColor = [UIColorredColor];

    

    [vaddBlockMethod:^(MyView *view) {

      self.view.backgroundColor =[UIColorunderPageBackgroundColor];

     }];

    

    [self.viewaddSubview:v];

    

}


- (void)didReceiveMemoryWarning

{

    [superdidReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


@end


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
回答: 在iOS开发中,可以使用Blockdelegate来实现一对多的回调。使用delegate时,首先需要定义一个delegate协议,其中包含回调方法。然后在需要进行回调的地方,设置delegate并调用回调方法。具体实现可以参考以下代码示例:\[2\] ``` // 定义delegate协议 protocol FirstCellDelegate: class { func firstCellBtnTap(_ cell: firstTableViewCell) } // 在需要进行回调的地方设置delegate并调用回调方法 weak var delegate: FirstCellDelegate? // 调用回调方法 if let delegate = self.delegate { delegate.firstCellBtnTap(self) } // 实现delegate回调方法 func firstCellBtnTap(_ cell: firstTableViewCell) { let cellIndexPath = tableView.indexPath(for: cell) print("delegate回调 section:\(cellIndexPath?.section ?? 0), row:\(cellIndexPath?.row ?? 0)") } ``` 另外,使用Block也可以实现一对多的回调。Block可以作为函数表达式传递给API,可以选择性地存储,并且可以被多个线程使用。Block不仅包含了在回调时需要执行的代码,还包含了执行期间所需的数据。具体实现可以参考以下代码示例:\[3\] ``` // 定义Block回调 typealias CallbackBlock = () -> Void // 在需要进行回调的地方使用Block进行回调 var callback: CallbackBlock? // 调用回调 callback?() ``` 通过使用Blockdelegate,可以实现一对多的回调,满足不同场景下的需求。 #### 引用[.reference_title] - *1* [Block实现iOS回调](https://blog.csdn.net/feelinghappy/article/details/119870367)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [iOS BlockDelegate的用法,各自优缺点及使用场景](https://blog.csdn.net/huangshanfeng/article/details/82106580)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值