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];
  • 相关阅读:
    抑郁症:2019年11月9日
    NOIP2018考前抱佛脚——图论基础复习
    NOIP2018考前抱佛脚——搜索复习
    NOIP2018考前抱佛脚——数据结构基础及STL实现
    题解 P2920 【[USACO08NOV]时间管理Time Management】
    agc030C Coloring Torus
    agc036B Do Not Duplicate
    agc034C Tests
    AFO
    agc005D ~K Perm Counting
  • 原文地址:https://www.cnblogs.com/mudy/p/4818764.html
Copyright © 2011-2022 走看看