【问题标题】:why is KVO not working on UIView subclass?为什么 KVO 不能在 UIView 子类上工作?
【发布时间】:2012-08-10 22:20:33
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

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

    忘记分配/初始化 contentView。

    【讨论】:

    • 所以这解决了问题?尽可能选择它作为答案 - 谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-18
    • 1970-01-01
    • 2021-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多