zoukankan      html  css  js  c++  java
  • block的简单使用

    一: 定义block 初始化

    #import <UIKit/UIKit.h>

     

    @interface LHQDemoView : UIView

    - (instancetype)initWithFrame:(CGRect)frame andCompelete:(void(^)(NSString *msg))block;

     

     

    - (instancetype)initWithFrame:(CGRect)frame andCompelete:(void(^)(NSString *msg))block{

        if(self = [super initWithFrame:frame]){

            UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 50, 50)];

            [btn setTitle:@"提示" forState:UIControlStateNormal];

            [btn addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];

            [self addSubview:btn];

            self.block = block;

        }

        return self;

    }

     

     

     

     

    二: 定义全局block

    @interface LHQDemoView()

    //block定义的时候一定要用copy

    /*

     block默认在栈中  栈中内存归系统管理

     系统管理有个弊端:到作用于结束就被干掉

     执行了一个copy操作之后,就会把block从栈中放到堆中

     会自动有一个强引用来指向它

     

     

     */

    @property(nonatomic,copy)void(^block)(NSString *);

     

    设置

    self.block = block;

     

     

     

     

    三: 给block赋值

    - (void)btnClicked: (UIButton *)btn{

        self.block(@"点击了某个按钮");

        NSLog(@"btnClicked");

    }

     

     

    四: 使用

      导入头文件

    #import "LHQDemoView.h"

    @interface ViewController ()

     

    @end

     

     

     LHQDemoView *demoView = [[LHQDemoView alloc]initWithFrame:CGRectMake(100, 200, 100, 100) andCompelete:^(NSString *msg) {

            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:msg delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];

            [alert show];

        }];

        [self.view addSubview:demoView];

     

     

     

     

     

     

     

  • 相关阅读:
    iOS 绕过https证书验证 请求数据
    RN import ** from ** 用法
    蓝牙开发笔记
    golang笔记
    python3 md5
    python3 zip压缩
    nginx应用
    zipimport.ZipImportError: can't find module 'encodings'
    python3 模块安装列表
    cmd笔记
  • 原文地址:https://www.cnblogs.com/LiLihongqiang/p/7086400.html
Copyright © 2011-2022 走看看