美文网首页
UI05_反向传值(17-08-09)

UI05_反向传值(17-08-09)

作者: Hilarylii | 来源:发表于2017-08-09 16:50 被阅读0次
//
//  ViewController.m
//  UI05_反向传值
//
//  Created by lanou3g on 17/8/9.
//  Copyright © 2017年 lanou3g. All rights reserved.
//

#import "ViewController.h"
#import "MyView.h"

@interface ViewController () <MyViewDelegate>

@property (nonatomic,retain) UILabel *label;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    MyView *myView = [[MyView alloc] initWithFrame:self.view.bounds];
    myView.delegate = self;
    [self.view addSubview:myView];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(100, 550, 100, 40)];
    label.backgroundColor = [UIColor yellowColor];
    self.label = label;
    [self.view addSubview:self.label];
}
- (void)getButtonIndex:(NSInteger)index {
    self.label.text = [NSString stringWithFormat:@"%ld",index];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

//
//  MyView.h
//  UI05_反向传值
//
//  Created by lanou3g on 17/8/9.
//  Copyright © 2017年 lanou3g. All rights reserved.
//

#import <UIKit/UIKit.h>

@protocol MyViewDelegate <NSObject>

- (void)getButtonIndex:(NSInteger)index;

@end

@interface MyView : UIView

@property (nonatomic,assign) id <MyViewDelegate>delegate;

@end

//
//  MyView.m
//  UI05_反向传值
//
//  Created by lanou3g on 17/8/9.
//  Copyright © 2017年 lanou3g. All rights reserved.
//

#import "MyView.h"

@implementation MyView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        for (int i = 0; i < 10; i++) {
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.frame = CGRectMake(100, 50+i*50, 50, 30);
            button.backgroundColor = [UIColor orangeColor];
            [button setTitle:@"touch" forState:UIControlStateNormal];
            [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
            //点击知道是第一个button
            button.tag = 1000+i;
            [self addSubview:button];
        }
    }
    return self;
}

- (void)buttonAction:(UIButton *)button {
    NSLog(@"button index = %ld", button.tag-1000);
    
    [self.delegate getButtonIndex:button.tag - 1000];
}

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

@end

相关文章

网友评论

      本文标题:UI05_反向传值(17-08-09)

      本文链接:https://www.haomeiwen.com/subject/okjqrxtx.html