zoukankan      html  css  js  c++  java
  • 代理的使用 一(helloworld级别)

    个人理解(估计,半年一年后,在看到这篇文章的时候,会觉得,当时真的弱爆了)

    当我们自定义view的时候,比如说view上面有几个按钮,那么我们在别的地方使用这个view的时候,怎么来处理这些点击事件呢。
     
    就可以使用代理来实现这个需求了(就是处理view上的按钮的点击事件)
     
    首先是先创建一个view,命名为ViewWithButtons,并且创建其对应的xib文件(这个在创建view的时候,勾选创建xib的那项并不能点击,所以需要我们手动创建:new->empty命名为ViewWithButtons.xib,然后在xib中,拖一个view进去,并且将这个view与ViewWithButtons关联起来)
    然后在这个视图上拖几个按钮,并且给上不同的tag值。将这几个按钮的点击事件连接到ViewWithButtons.m中

    ViewWithButtons.h部分的代码。

    @protocol ViewWithBuutonsDelegate<NSObject>

    @required

    -(void)buttonClickedWithTag:(NSInteger)tag;

    @end

    @interface ViewWithButtons : UIView

    @property(nonatomic)id <ViewWithBuutonsDelegate> delegate;

    @end

     
    .m部分的代码

    - (IBAction)buttonClick:(UIButton *)sender {

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

            [self.delegate buttonClickedWithTag:sender.tag];

        }   

    }

    我理解的就是,如果self.delegate responds 了后面的方法,那么,就,,
     
    在控制器部分的代码是:

    #import "ViewController.h"

    #import "ViewWithButtons.h"

    @interface ViewController ()<ViewWithBuutonsDelegate>

    @end

    @implementation ViewController

    - (void)viewDidLoad {

        [super viewDidLoad];

        ViewWithButtons *view = [[[NSBundle mainBundle]loadNibNamed:@"ViewWithButtons" owner:self options:nil]lastObject];

        view.delegate = self;

        

        [self.view addSubview:view];

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

    }

    -(void)buttonClickedWithTag:(NSInteger)tag{

        NSLog(@"%lu",tag);

    }

     
     
    需要注意的是,我们在使用由xib创建的视图的时候,需要用到的方法是[[[NSBundle mainBundle]loadNibNamed:@"ViewWithButtons" owner:selfoptions:nil]lastObject];
  • 相关阅读:
    博客园的第一篇博客
    I-如何办好比赛
    塞特斯玛斯塔
    字典序最大的子序列
    百练POJ 1657:Distance on Chessboard
    百练POJ2750:鸡兔同笼
    HDU3790最短路径问题
    HDU 2544最短路Dijkstra算法
    快速幂【倍增+二分】
    树的高度
  • 原文地址:https://www.cnblogs.com/mudy/p/4818764.html
Copyright © 2011-2022 走看看