iOS talks about proxy value transfer again

The example of this post is: there are two interfaces, A and B. The effect to be achieved is to let A jump to B first, and then there is a color parameter in B. When B jumps to A, pass the color parameter. Give A, use this color in A to change the color of its own interface.

Step 1: In the sender (interface B), make the protocol (declared in the .h header file)
// 协议名一般以本类的类名开头+Delegate (包含前缀)
 @protocol ConfigViewControllerDelegate <NSObject> // 声明协议方法,一般以类名开头(不需要前缀) - (void)changeBgColor:(UIColor *)color;

B 是委托 1定义协议, 2声明代理, 3调用协议。
Step 2: Proxy the protocol in the .h file in the sender (interface B). Outgoing classes -- declare proxies.  
@interface ConfigViewController : UIViewController
// id即表示谁都可以设置成为我的代理 @property (nonatomic,weak) id<ConfigViewControllerDelegate> delegate; // ARC使用weak,MRC使用assign @end 
Step 3: Notify the agent in the method in the sender (interface B) ( most important step )
  //这一步一般是在B跳转到A的方法中实现的,我是在B中创建了一个Button,让这个通知代理在Button中跳转方法中实现。 
 if ([self.delegate respondsToSelector:@selector(changeBgColor:)]) { 
    // 加入if语句就是先判断在界面A中是否有changeBgColor这个方法,当有这个方法的时候,才进行代理传值。 //一般会先实例化出一个color的对象,在进行代理传值的时候,是带着这个color一起传递过去的。 [self.delegate changeBgColor:color]; //这里的self是界面B,self.delegate就是界面A了 调用(在第4步和第5步的设置中设置了) }

A 1 follow the protocol 2 set the proxy 3 implement the protocol incoming class ---- proxy class
Step 4: Follow the protocol in the receiver (interface A).
  @interface ViewController () <ConfigViewControllerDelegate>
Step 5: Set yourself up as a proxy in the receiver (interface A).
  ConfigViewController *testVC = [[ConfigViewController alloc] init];
  testVC.delegate = self;
Step 6: Implement the methods in the protocol in the receiver (interface A).
  - (void)changeBgColor:(UIColor *)color{
  self.view.backgroundColor = color;
  }



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324686982&siteId=291194637