• iOS 设置代理过程


    iOS设置代理的过程 (以模拟 button 作用为例)

    1.写协议

      新建一个名为 MyButton 的文件,继承于 UIView,在该文件里 声明协议 myDelegate

    2.写协议方法

      为声明的协议添加方法 

    3.定义一个遵守协议的属性

      前三步代码如下:

     1 #import <UIKit/UIKit.h>
     2 @class MyButton;
     3 //第一步:写协议
     4 @protocol myDelegate <NSObject>
     5 //第二步:写协议方法 (参数要在上面声明:@class MyButton;)
     6 - (void)changeColor:(MyButton *) myButton;
     7 @end
     8 
     9 @interface MyButton : UIView
    10 //第三步:写一个myDelegate属性
    11 @property (nonatomic , assign)id<myDelegate>  delegate;
    12 
    13 @end

    4.写一个调用协议的方法

      写touchesBegan 方法

    5.调用协议方法

      4,5步代码:

    1 //第四步 写touchesBegan 方法
    2 - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    3     //第五步调用协议的方法
    4     [_delegate changeColor:self];
    5 }

    6.遵守协议

      让要实现协议的类遵守协议

     1 //第六步 遵循协议 2 @interface RootViewController : UIViewController <myDelegate> 

    7.设置代理

      self.rootView.myButton.delegate = self; 

    8.实现协议方法

    1 //第八步 实现协议中的方法
    2 - (void)changeColor:(MyButton *)myButton{
    3     myButton.backgroundColor = [UIColor colorWithRed:arc4random()%256/255.0 green:arc4random()%256/255.0 blue:arc4random()%256/255.0 alpha:1];
    4 }
  • 相关阅读:
    IPC机制 用Messenger进行进程间通信
    Android 远程Service
    创建前台 Service
    可见性和可达性,C#和C++
    set,map存储问题
    const形参和非const形参
    数组const形参和非const形参的区别
    switch 变量定义报错
    修改oracle用户密码永不过期
    面向对象语言成员变量方法可见性在继承中的变化
  • 原文地址:https://www.cnblogs.com/Ager/p/4907437.html
Copyright © 2020-2023  润新知