import "ViewController.h"
import "tempView.h"
@interface ViewController ()
@property (nonatomic,strong) tempView *tempView;
@end
@implementation ViewController
-
(tempView *)tempView
{
if (!_tempView) {
_tempView = [[tempView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];[_tempView addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew context:nil]; [self.view addSubview:_tempView];
}
return _tempView;
} -
(void)viewDidLoad {
[super viewDidLoad];[self tempView];
} -
(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
self.tempView.name = @"2345";
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
//第一个参数就是观察的属性名
//第二个参数是观察对象
//第三个参数是改变的值
//第四个参数是说明
NSLog(@"str 变了");
NSLog(@"%@",keyPath);
if([keyPath isEqualToString:@"name"])//观察的str属性改变了 记准了哈!!!是属性名字!!!不是属性的值,,所以会进来
{
NSLog(@"%@",change[@"new"]);
self.view.backgroundColor = [UIColor colorWithRed:arc4random()%255/255.0 green:arc4random()%255/255.0 blue:arc4random()%255/255.0 alpha:arc4random()%255/255.0];
}
else{
//该干嘛干嘛
}
}
tempView
import <UIKit/UIKit.h>
@interface tempView : UIView
@property (nonatomic,copy) NSString *name;
@end
import "tempView.h"
@interface tempView ()
@property (nonatomic,weak) UIView *tempView;
@end
@implementation tempView
-
(instancetype)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame]) {UIView *view = [[UIView alloc] initWithFrame:self.bounds]; view.backgroundColor = [UIColor redColor]; [self addSubview:view]; self.name = @"123"; self.tempView = view;
}
return self;
}
@end
网友评论