iOS如何实现传值---target-action设计模式

步骤:

1.给B类添加属性

@property (nonatomic, assign) id target;
@property (nonatomic, assign) SEL action;

2.如何调用方法

    [self.target performSelector:self.action];
3.如何在A类调用

设置B类所生成的对象.target = self;

设置B类所生成的对象.action = @selector(A类中的方法C);

4.在A类中添加方法C

- (void)C
{
    NSLog(@"========");
}

代码例子:

TestView.h

//
//  TestView.h
//  target-action设计模式
//
//  Created by 萨斯辈的呼唤 on 14-6-10.
//  Copyright (c) 2014年 萨斯辈的呼唤. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface TestView : UIView

@property (nonatomic, assign) id target;
@property (nonatomic, assign) SEL action;

@end

TestView.m

//
//  TestView.m
//  target-action设计模式
//
//  Created by 萨斯辈的呼唤 on 14-6-10.
//  Copyright (c) 2014年 萨斯辈的呼唤. All rights reserved.
//

#import "TestView.h"

@implementation TestView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.target performSelector:self.action];
}

@end

在MainViewController.m中

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    TestView *test = [[TestView alloc] initWithFrame:CGRectMake(0, 0, 300, 200)];
    test.backgroundColor = [UIColor redColor];
    [self.view addSubview:test];
    test.target = self;
    test.action = @selector(show);
}

- (void)show
{
    NSLog(@"========");
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值