开发者

Changing the value of an NSImageView when it is edited via the control

I have an NSImageView which is set to editable. I would like to be able to revert to a default image when the user deletes the image. I've tried changing the value that the NSImageView is b开发者_如何学Pythonound to in the setter, but the getter is not called afterwards, so the NSImageView is blank, despite the bound value being set to another image. Here is the setter code:

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

How should I make the NSImageView update it's value?


You don't need to send yourself willChangeValueForKey: and didChangeValueForKey: messages inside of a setter method. When something starts observing your currentDeviceIcon property, KVO wraps your setter method to post those notifications automatically whenever something sends your object a setCurrentDeviceIcon: message.

So, the method should look like this:

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

And then you need to send this object setCurrentDeviceIcon: messages to change the value of the property. Don't assign directly to the currentDeviceIcon instance variable, except in this method and in init or dealloc (in the latter two, you should generally not send yourself any other messages).

If that's not working for you, either your image view is not bound, or it is bound to the wrong object. How are you binding it? Can you post the code/a screenshot of the Bindings inspector?


why you can use selector to NSImageview example

-(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"];
}

Here NSArrayController is your array controller name.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜