SelectedRow of NSOutlineView always returns -1 - cocoa

I have a View-based NSOutlineView, and have in the class a selection change event:
- (void)outlineViewSelectionDidChange:(NSNotification *)notification
{
NSLog(#"Selected Row inside:%ld",[self selectedRow]);
}
This is the way I create my NSOutlineView:
ovc = [[OutlineViewController alloc] init];
[myOutlineView setDelegate:(id<NSOutlineViewDelegate>)ovc];
[myOutlineView setDataSource:(id<NSOutlineViewDataSource>)ovc];
MyOutlineView is created in IB.
Every time I click on a row, the event gets fired, however the result is always -1.
NSLog(#"Item 0:%#",[self viewAtColumn:1 row:0 makeIfNecessary:YES]);
Always returns NULL.
Is there something specific I should do ? Thanks.
=== EDIT ===
I have published my simplified code showing the issue: http://www.petits-suisses.ch/OutlineView.zip

Instead of checking the selectedRow of self object, which is just a object initialized in AppController which is a wrong instance. You need to check on the notification object as shown below.
NSLog(#"Selected Row:%ld",[[notification object] selectedRow]);
Also clickedRow is meaningful in the target’s implementation of the action. So the clickedRow gives correct value if checked inside a Action or DoubleAction method.

Your NSOutlineView "Controller" class is actually a subclass of NSOutlineView, this is different then the NSOutLineView in your XIB file. If you look at the notification object being sent it is an instance of NSOutlineView, not "OutlineViewController", therefore you are calling selectedRow on an incorrect instance.
This code should be place in a subclass of NSViewController as opposed to NSOutlineView. Then create an outlet from the outlineView to the controller.

Related

NSTableView double click action not being called

I have an NSViewController which is set as the datasource and delegate of a single column tableview which uses a NSTableCellView subclass. I want to respond to a double-click on a row so I've set the table column to be not editable and have the following code:
myViewController.h
- (IBAction)didDoubleClickFolderRow:(id)sender;
myViewController.m
- (void)awakeFromNib
{
[self.table setDoubleAction:#selector(didDoubleClickFolderRow:)];
[self.table setTarget:self];
}
- (IBAction)didDoubleClickFolderRow:(id)sender
{
NSLog(#"yep a row was double-clicked!");
}
Yet the method never gets called. What am I missing?
Rather obscurely this turns out to have been caused by me overriding resignFirstResponder on another view, to get around another problem.
Not sure why a double click on a tableview fires a resignFirstResponder, but it seems to.

View-based NSTableView + NSButton

I've got a view-based NSTableView, using Cocoa Bindings to change the values of some labels and images in the cell. It all works great. However, I want to add a button to the cell. I've got the button working, but its action method only has the button as sender, which means I have no idea of the content of the cell that the button is in. Somehow I need to store some extra data on the button - at the very least the row index that the button is in. I subclassed NSButton and used my subclass in the cell, but Interface Builder doesn't know about the extra property so I can't bind to it. If I wanted to bind it in code, I don't know the name of the object or keypath that would be passed to it.
How can I get this to work?
You can use rowForView in your action method to get the row value
- (IBAction)doSomething:(id)sender
{
NSInteger row = [_myTableView rowForView:sender];
}
You can use the Identity field in Interface Builder to associate a table cell view from the nib with an instance in your code:
Additionally you have to implement - tableView:viewForTableColumn:row: in your table view's delegate. (Don't forget to connect the delegate in IB)
- (NSView*)tableView:(NSTableView*)tableView viewForTableColumn:
(NSTableColumn*)tableColumn row:(NSInteger)row
{
SSWButtonTableCellView *result = [tableView makeViewWithIdentifier:#"ButtonView" owner:self];
result.button.title = [self.names objectAtIndex:row][#"name"];
result.representedObject = [self.names objectAtIndex:row];
return result;
}
I added representedObject property in my NSTableCellView subclass, which I set in the above table view delegate method.
Your custom table cell view can later use that object in it's action. e.g.:
- (IBAction)doSomething:(id)sender
{
NSLog(#"Represented Object:%#", self.representedObject);
}

OS X - How can a NSViewController find its window?

I have a Document based core data app. The main document window has a number of views, each controlled by its own custom NSViewController which are switched in as necessary. I want each of these view controllers to be able to drop down a custom modal sheet from the document window. However because the views are separate and not in the MyDocument nib I cannot link the view to the document window in IB. This means that when I call
[NSApp beginSheet: sheetWindow modalForWindow: mainWindow modalDelegate: self didEndSelector: #selector(didEndSheet:returnCode:contextInfo:) contextInfo: nil];
I’m supplying nil for mainWindow and the sheet therefore appears detached.
Any suggestions?
Many Thanks
You can use [[self view] window]
Indeed, it's self.view.window (Swift).
This may be nil in viewDidLoad() and viewWillAppear(), but is set properly by the time you get to viewDidAppear().
One issue with the other answers (i.e., just looking at self.view.window) is that they don't take into account the case that when a view is hidden, its window property will be nil. A view might be hidden for a lot of reasons (for example, it might be in one of the unselected views in a tab view).
The following (swift) extension will provide the windowController for a NSViewController by ascending the view controller hierarchy, from which the window property may then be examined:
public extension NSViewController {
/// Returns the window controller associated with this view controller
var windowController: NSWindowController? {
return ((self.isViewLoaded == false ? nil : self.view)?.window?.windowController)
?? self.parent?.windowController // fallback to the parent; hidden views like those in NSTabView don't have a window
}
}
If your controller can get access to the NSDocument subclass, you can use -windowForSheet
more about Tim Closs answer :
-(void)viewDidAppear
{
self.view.window.title = #"title-viewDidAppear"; //this only works when and after viewDidAppeer is called
}
-(void)viewWillDisappear
{
self.view.window.title = #"title-viewWillDisappear"; //this only works before and when viewWillDisappear is called
}

Disable/Enable NSButton if NSTextfield is empty or not

I´m newbie with cocoa. I have a button and a textField in my app. I want the button disabled when the textfield is empty and enabled when the user type something.
Any point to start? Any "magic" binding in Interface Builder?
Thanks
[EDITED]
I´ve tried to set the appDelegate as the NSTextfield´s delegate and added this method (myTextfield and myButton are IBOutlets):
- (void)textDidChange:(NSNotification *)aNotification
{
if ([[myTextField stringValue]length]>0) {
[myButton setEnabled: YES];
}
else {
[myButton setEnabled: NO];
}
}
But nothing happens...
I´ve tried to set the appDelegate as the NSTextfield´s delegate and added this method (myTextfield and myButton are IBOutlets):
- (void)textDidChange:(NSNotification *)aNotification
{
if ([[myTextField stringValue]length]>0) {
[myButton setEnabled: YES];
}
else {
[myButton setEnabled: NO];
}
}
That's the hard way, but it should work just fine. Either you haven't hooked up the text field's delegate outlet to this object, you haven't hooked up the myTextField outlet to the text field, or you haven't hooked up the myButton outlet to the button.
The other way would be to give the controller a property exposing the string value, bind the text field's value binding to this stringValue property, and bind the button's enabled binding to the controller's stringValue.length.
You could also give the controller two properties, one having a Boolean value, and set that one up as dependent upon the string property, and bind the button to that. That's a cleaner and possibly more robust solution, though it is more work.
Here's a solution using bindings.
Below I setup a NSTextField that is bound to the file owner's "text" property. "text" is a NSString. I was caught by "Continuously Updates Value". Thinking my solution didn't work but really it wasn't updating as the user typed, and only when the textfield lost focus.
And now setting up bindings on the button, simply set its enabled state to the length of the file owner's text property.
Annd, the working product.
If you use controlTextDidChange instead of textDidChange, you can get rid of the notification stuff and just rely on being the NSTextField's delegate.
Thanks Peter. What I missed (in my hard way version) is this piece of code in the awakeFromNib in the appDelegate:
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center addObserver:self selector:#selector(textDidChange:) name:NSControlTextDidChangeNotification object:myTextField];
It works perfect. Now I´m trying the easy way, but I´m afraid I´m not still good enough with the bindings.
To bind the property
#property (retain) IBOutlet NSString *aStringValue;
with the textfield´s value, what I have to use in IB for "Bind to:", "Controller Key" and "Model Key Path"?

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 bound 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.

Resources