• 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];

     

     

     

     

     

     

     

  • 相关阅读:
    一个很好的在线测试编辑器(可以在线运行很多程序)
    基于angular的route实现单页面cnodejs
    微博
    jsonp跨域再谈
    打开IIS的快捷键
    PHPCMS笔记第二弹
    phpcms ——模板标签详细使用说明
    PHP流程管理,堪比小小程序
    PHP的简单易懂文件管理,可实现基本功能
    使用php ajax写省、市、区、三级联动
  • 原文地址:https://www.cnblogs.com/LiLihongqiang/p/7086400.html
Copyright © 2020-2023  润新知