zoukankan      html  css  js  c++  java
  • iOS开发之block

    iOS开发之block

    1.什么是block,block的作用

    block      代码块,解决回调,理解为“匿名函数”,定义在方法里面(先定义,再使用)

    2.block的基本使用(语法)

    3.block在开发中的应用

    在A、B两个界面之间传值,改变背景颜色

    A界面

    #import "SecondViewController.h"
    
    @interface SecondViewController ()
    {
        //定义block变量,为了保存传人的参数
        void (^_action)(NSString *color);
    }
    @end
    
    @implementation SecondViewController
    
    - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
    {
        self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
        if (self) {
            // Custom initialization
        }
        return self;
    }
    
    - (void)viewDidLoad
    {
        [super viewDidLoad];
        // Do any additional setup after loading the view.
        
        self.view.backgroundColor = [UIColor brownColor];
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        button.frame = CGRectMake(100, 200, 100, 30);
        [button setTitle:@"切换" forState:UIControlStateNormal];
        [button addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:button];
        
        
    }
    -(void)btnClick:(UIButton *)button
    {
        
        if (_action) {
            _action(@"blue");
        }
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    -(void)setChangeBackgroundColor:(void (^)(NSString *))action
    {
        _action = action;
    }

    B界面

    -(void)createView
    {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        button.frame = CGRectMake(100, 200, 100, 30);
        [button setTitle:@"切换" forState:UIControlStateNormal];
        [button addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:button];
        
        
    }
    -(void)btnClick:(UIButton *)button
    {
        
        
        
        SecondViewController *svc = [[SecondViewController alloc] init];
        
        [svc setChangeBackgroundColor:^(NSString *color) {
            if ([color isEqualToString:@"blue"]) {
                self.view.backgroundColor = [UIColor blueColor];
            }
        }];
        
        [self presentViewController:svc animated:YES completion:nil];
    }
  • 相关阅读:
    快速排序(详解)
    14.linux-platform机制实现驱动层分离(详解)
    13.Linux键盘按键驱动 (详解)
    Linux-hexdump命令调试event驱动—详解(13)
    Android开发final的用法
    Android控件RecyclerView的基本用法
    搜索关键词分析——以个人博客网站为例
    java.net.SocketException: Software caused connection abort: socket write error
    Android layout属性大全
    java中 label 配合 break continue 使用方法
  • 原文地址:https://www.cnblogs.com/NFli/p/4399240.html
Copyright © 2011-2022 走看看