Search code examples
objective-cmacoscocoanstableviewnsindexset

NSIndexSet not set when user press enter after NSAlert


I have a very simple Mac app, that at one particular time, a button brings up a NSAlert with an input field. After that I take some actions on a NSTableView. It works fine if the user presses the OK button, but if the user presses ENTER, it does not define the selectedrows

 NSAlert *alert = [[NSAlert alloc] init];
[alert setMessageText:@"Damage"];
[alert addButtonWithTitle:@"Ok"];
[alert addButtonWithTitle:@"Cancel"];
NSInteger damage = 0;
NSTextField *input = [[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, 200, 24)];
[input setStringValue:@""];
[[alert window]setInitialFirstResponder:input];

[alert setAccessoryView:input];
NSInteger button = [alert runModal];
if (button == NSAlertFirstButtonReturn) {
     damage = [input integerValue];
} else if (button == NSAlertSecondButtonReturn) {

}

//data
NSIndexSet *set = [self.tableView selectedRowIndexes];

NSUInteger index = [set lastIndex];

The index has the value of NSNotFound.

Could someone help fix it? Tks


Solution

  • So, I basically needed to add a key equivalent to the ENTER and it solved the issue:

     NSAlert *alert = [[NSAlert alloc] init];
    [alert setMessageText:@"Damage/Heal"];
    [alert addButtonWithTitle:@"Ok"];
    [alert addButtonWithTitle:@"Cancel"];
    NSInteger damage = 0;
    NSTextField *input = [[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, 200, 24)];
    [input setStringValue:@""];
    [[alert window]setInitialFirstResponder:input];
    
    [alert setAccessoryView:input];
    alert.buttons[0].keyEquivalent=@"\r";//new code
    NSInteger button = [alert runModal];
    if (button == NSAlertFirstButtonReturn) {
        damage = [input integerValue];
    } else if (button == NSAlertSecondButtonReturn) {
    
    }