iOS每日一记————————简单的实现委托 Block代码块 功能 和简单的自定义View

来源:互联网 发布:docker连接外部数据库 编辑:程序博客网 时间:2024/04/18 21:20

╮(╯▽╰)╭。。。。
MVC我的理解并不是特别深入 只能理解其中的一点点东西 ,,,,V需要从C中 剥离出来 其实说白了 就像Xib创建一样 Xib你创建了之后 可以在上面托各种控件 其实那个Xib文件就相当于View 只是用来视图显示的  之后你拖了Xib 控件之后是不是要连线呢 而且会自动生成IBout @property(nonatomic,weak) 之所以用weak 那是因为当前主view自动对ib创建的控件自动添加强引用 所以你不需要用strong。。。。 当年创建Button 的时候是不是可以连线生成方法呢 那其实就类似于 你自己创建个butoon 给他写个委托 或者 block 恩 通知也是可以的 从而实现对C的通信

自定义的Uiview里面的.h文件

#import <UIKit/UIKit.h>
@protocol TestViewDelegate <NSObject>//声明一个代理
@optional
- (void)toRemove;//代理方法
@end
@interface TestView : UIView 
@property (nonatomic,copy)void(^ClickBlock)(NSString *str);//传值得block
@property (nonatomic,assign) id<TestViewDelegate>delegate;
@end


自定义View里面的.h文件

#import "TestView.h"


@interface TestView()<UIGestureRecognizerDelegate>
{
    NSInteger count;
}
@property (nonatomic,strong) UIView *clickView;
@end


@implementation TestView


- (instancetype)initWithFrame:(CGRect)frame{
    
    
    self = [super initWithFrame:frame];
    if (self) {
       
        self.clickView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 150, 150)];
        self.clickView.backgroundColor = [UIColor redColor];
        self.clickView.userInteractionEnabled = YES;
        [self addSubview:self.clickView];
        UITapGestureRecognizer *GestureRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(GestureRecognizer)];
        [self.clickView addGestureRecognizer:GestureRecognizer];
    }
    
    return self;
}




- (void)GestureRecognizer{
    if (count%2==0) {
        
        if ([self.delegate respondsToSelector:@selector(toRemove)]) {
            [self.delegate toRemove];
        }
        
    } else{
    self.ClickBlock(@"");
    }
    
    count++;
}

VC里面的.m文件
#import "ViewController.h"
#import "TestView.h"


@interface ViewController ()<TestViewDelegate>//实现自定义View的代理


@end


@implementation ViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    TestView *VC = [[TestView alloc]initWithFrame:CGRectMake(50, 100, 300, 300)];
    VC.backgroundColor = [UIColor blueColor];
    VC.ClickBlock = ^(NSString *str){
        self.view.backgroundColor = [UIColor greenColor];
    };
    VC.delegate =self;//声明代理的对象是谁
    [self.view addSubview:VC];
    // Do any additional setup after loading the view, typically from a nib.
}


- (void)toRemove{
    self.view.backgroundColor = [UIColor blackColor];
}








0 0