0

我有一个 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 没有触发的任何想法?

4

1 回答 1

2

对不起……我猜是剥夺睡眠……

忘记分配/初始化 contentView。

于 2012-08-10T22:37:04.160 回答