【问题标题】:Changing the value of an NSImageView when it is edited via the control通过控件编辑时更改 NSImageView 的值
【发布时间】:2020-04-28 08:53:16
【问题描述】:

我有一个设置为可编辑的 NSImageView。当用户删除图像时,我希望能够恢复为默认图像。我尝试更改 NSImageView 在 setter 中绑定的值,但之后不会调用 getter,因此 NSImageView 是空白的,尽管绑定值被设置为另一个图像。这是设置器代码:

-(void)setCurrentDeviceIcon:(NSImage *)newIcon {
    [self willChangeValueForKey:@"currentDeviceIcon"];
    if(newIcon == nil)
        newIcon = [currentDevice defaultHeadsetIcon];
    currentDeviceIcon = newIcon;
    [self setDeviceChangesMade:YES];
    [self didChangeValueForKey:@"currentDeviceIcon"];   
}

我应该如何让 NSImageView 更新它的值?

【问题讨论】:

    标签: cocoa nsimageview


    【解决方案1】:

    您不需要在 setter 方法中向自己发送 willChangeValueForKey:didChangeValueForKey: 消息。当有东西开始观察你的 currentDeviceIcon 属性时,KVO 会包装你的 setter 方法,以便在有东西向你的对象发送 setCurrentDeviceIcon: 消息时自动发布这些通知。

    所以,方法应该是这样的:

    -(void)setCurrentDeviceIcon:(NSImage *)newIcon {
        if(newIcon == nil)
            newIcon = [currentDevice defaultHeadsetIcon];
        currentDeviceIcon = newIcon;
        [self setDeviceChangesMade:YES];
    }
    

    然后你需要发送这个对象setCurrentDeviceIcon:消息来改变属性的值。不要直接赋值给currentDeviceIcon 实例变量,除了在这个方法和initdealloc 中(在后两者中,你通常不应该给自己发送任何其他消息)。

    如果这对您不起作用,则您的图像视图未绑定,或者绑定到错误的对象。你是怎么绑定的?您可以发布绑定检查器的代码/屏幕截图吗?

    【讨论】:

    • 对,这似乎仍然不起作用。我很确定绑定很好(以防万一,SS 附在原始帖子上)。我想也许我有点不清楚 - 当通过控制器更改图像时,控件工作得很好,这是 nsimageview 允许用户在关注它时按下删除键,图像将设置为 nil。程序随后调用 setter,但不调用 getter。
    • 哦,我明白了。对不起;我的误解。
    【解决方案2】:

    为什么你可以使用选择器来NSImageview 例子

    -(IBAction)setImage:(id)sender
    {
        NSString *icon_path = [NSString stringWithFormat:@"%@/%@",[[NSBundle mainBundle]resourcePath],@"default_icon.png"];
        NSData *imgdata = [NSData dataWithContentsOfFile:icon_path];
        [[[self NSArrayController] selection] setValue:imgdata forKeyPath:@"currentDeviceIcon"];
    }
    

    这里NSArrayController 是您的阵列控制器名称。

    【讨论】:

      猜你喜欢
      • 2010-10-15
      • 2018-12-14
      • 1970-01-01
      • 2012-03-01
      • 2014-03-02
      • 2012-05-10
      • 2019-01-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多