1.添加绿色的view,MJViewController对象作为owner
NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"MyView" owner:self options:nil];
UIView *greenView = array[0];
[self.view addSubview:greenView];
2.添加蓝色的view,Dog对象作为owner
UIView *blueView = [[NSBundle mainBundle] loadNibNamed:@"HisView" owner:_d2 options:nil][0];
blueView.center = CGPointMake(160, 200);
[self.view addSubview:blueView];
3.owner的机制为代理模式
方法/步骤
- 1
MJViewController.h
#import <UIKit/UIKit.h>
@interface MJViewController : UIViewController
- (IBAction)leftClick;
- (IBAction)rightClick;
@end
- 2
MJViewController.m
#import "MJViewController.h"
#import "Dog.h"
@interface MJViewController ()
{
Dog *_d1;
Dog *_d2;
}
@end
@implementation MJViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// 1.加载xib文件
NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"MyView" owner:self options:nil];
UIView *greenView = array[0];
// 2.添加到控制器的view里面去
[self.view addSubview:greenView];
// 3.
// UIButton *left = (UIButton *)[greenView viewWithTag:10];
// [left addTarget:self action:@selector(leftClick) forControlEvents:UIControlEventTouchUpInside];
//
// UIButton *right = (UIButton *)[greenView viewWithTag:20];
// [right addTarget:self action:@selector(rightClick) forControlEvents:UIControlEventTouchUpInside];
_d1 = [[Dog alloc] init];
_d1.age = 10;
_d2 = [[Dog alloc] init];
_d2.age = 20;
// 添加蓝色的view
UIView *blueView = [[NSBundle mainBundle] loadNibNamed:@"HisView" owner:_d2 options:nil][0];
blueView.center = CGPointMake(160, 200);
[self.view addSubview:blueView];
}
- (void)leftClick
{
NSLog(@"left------");
}
- (void)rightClick
{
NSLog(@"right------");
}
@end
- 3
Dog.h
#import <Foundation/Foundation.h>
@interface Dog : NSObject
@property (nonatomic, assign) int age;
- (IBAction)btnClick;
@end
- 4
Dog.m
#import "Dog.h"
@implementation Dog
- (void)btnClick
{
NSLog(@"%d岁的狗在汪汪.....", _age);
}
/*
- (NSArray *)loadNibNamed:(NSString *)name owner:(id)owner options:(NSDictionary *)options
{
// 解析HisView.xib文件
// 创建Objects下面的所有对象
// 创建view
UIView *blue = [[UIView alloc] init];
blue.backgroundColor = [UIColor blueColor];
//....设置其他属性
// 创建按钮
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[btn setTitle:@"我是按钮" forState:UIControlStateNormal];
[btn addTarget:owner action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];
// ....设置其他属性
[blue addSubview:btn];
// 创建文本输入框
UITextField *field = [[UITextField alloc] init];
// ... 设置其他属性
return @[ blue, field];
}
*/
@end
- 5
MyView.xib
- 6
HisView.xib