为什么KVO不在UIView子类上工作?

时间:2012-08-10 22:20:34

标签: ios cocoa-touch uiview key-value-observing

我有一个UIView子类,后者又有一个contentView,在公共头中声明如下:

@property (nonatomic,retain)UIVivew* contentView;

我试图在contentView的框架发生变化时收到KVO通知但是我的UIView子类中没有调用observeValueForKeyPath方法:

@implementation MyView


@synthesize contentView = _contentView;


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

        [self.contentView addObserver:self 
                           forKeyPath:@"frame" 
                              options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld) 
                              context:nil];
    }   
    return self;
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqualToString:@"frame"]) {
        CGRect newContentFrame = [[change objectForKey:NSKeyValueChangeNewKey] CGRectValue];
        CGRect selfNewFrame = self.frame;
        selfNewFrame.size = CGSizeMake(newContentFrame.size.width + 10, newContentFrame.size.height + 10);
        self.frame = selfNewFrame;
    }

    [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}

关于为什么KVO没有解雇的任何想法?

1 个答案:

答案 0 :(得分:2)

对不起......我觉得睡眠不足......

忘记分配/初始化contentView。