NSPopUpButton set it to the first item - macos

I have a clear button in my Mac OS app.
When the button is pressed, it clears all the values of the form and resets the NSPopUpButton to the first item.
The question is how do I change the NSPopUpButton control with code.
Thanks

You can call:
Objective C:
[myPopupButton selectItemAtIndex:0]
Swift:
myPopupButton.selectItem(at: 0)
See here for details.

When argument is 0 it means nil, and that works. If you put other number (for example 2 ) this will not work because the argument is not number!!!

Related

How can I determine what part of text in a scroll view is visible on screen from an Xcode UI test?

I'm new to the Xcode User Interface testing framework. I can successfully manipulate the screen elements, but cannot work out how to produce a meaningful assertion about what text is visible in a scrolling view.
The test I would like to write would go as follows: launch the app, type lots of text into a text view (enough that the first line scrolls out of view), assert that the first line of text is not visible, scroll the view back up to the top, then assert that the first line is now visible. Note that the purpose of this test is to ensure my app has wired things up correctly, not to test Apple's code.
XCUIApplication allows me to type into my NSTextView instance, and also allows me to scroll the associated NSScrollView. But how do I assert whether the first line of text is currently visible? The value attribute on XCUIElement provides the entire text content of the view, whether or not it is currently displayed.
The accessibilityRange(forLine:) and accessibilityString(for:) methods on NSTextView would be ideal, but I can't see how to access them as the UI test only has access to an XCUIElement, not the underlying NSTextView.
Have I missed something, or is there a better way to approach this?
If you set the accessibility identifier in the storyboard or in code for the text view you can get the text view via (assuming you gave it the id "textview1" and the window it's in has the default accessibility identifier of "Window"):
let textview1TextView = app.windows["Window"].textViews["textview1"]
but that won't actually get you what you need.
Instead, set the accessibility identifier of the scrollview and get that:
let scrollview = app.windows["Window"].scrollViews["scrollview1"]
Then use that to get the scrollbars (you should only have one in this case; you can use scrollbars.count to check.
let scrollbars = scrollview.scrollBars
print("scrollbars count: \(scrollbars.count)")
Then you can use the value attribute of the scrollbar to get it's value:
(you're converting a XCUIElemenTypeQueryProvider into an XCUIElement so you can get it's value):
let val = scrollbars.element.value
it will be 0 at the top and a floating point value when scrolled (one line of text in my test code showed a value of {{0.02409638554216868}}.
Documentation that will help you explore further:
XCUIElementTypeQueryProvider
XCUIElementAttributes
Note that you can put a breakpoint in the middle of your test, run it and then use the debugger console to examine things:
(lldb) po scrollbars.element.value
t = 749.66s Find the ScrollBar ▿ Optional<Any>
- some : 0
(lldb) po scrollbars.element.value
t = 758.17s Find the ScrollBar ▿ Optional<Any>
- some : 0.05421686746987952
and while in the debugger you can even interact with your app's window to scroll it manually (which is what I did between typing in those two po calls), or perhaps add text and so on.
OK OP now noted that they're interested in the specific text showing or not rather than the first line in view or not (which is what I previously answered above).
Here's a bit of a hack, but I think it'll work:
Use XCUICoordinate's click(forDuration:, thenDragTo:) method to select the first line of text (use the view frame to calculate coordinates) and then use the typeKey( modifierFlags:) to invoke the edit menu "copy" command. Then use NSPasteboard methods to get the pasteboard contents and check the text.
Here's a quick test I did to validate the approach (selecting the first line of text using XCUICoordinate as noted above is left as an exercise for the reader):
NSPasteboard.general.clearContents()
// stopped at break point on next line and I manually selected the text of the first line of text in my test app and then hit continue in the debugger
textview1TextView.typeKey("c", modifierFlags:.command)
print( NSPasteboard.general.pasteboardItems?.first?.string(forType: NSPasteboard.PasteboardType.string) ?? "none" );
-> "the text of the first line" was printed to the console.
Note that you can scroll the selection off screen so you have to not scroll after doing the select or you won't be getting the answer you want.

How to deselect the contents of a TextField in swift

I have a simple desktop app where a TextField should be focused when the window loads. I have this working, but it's a little annoying that, having loaded the users content into the TextField, the entire contents of the field become selected automatically. The user may want to start editing the content, but they will rarely/never want to replace it all at once (imagine a text editor doing this, to see what I mean).
I see there is an Action for selectAll: but what I want is the opposite Action of selectNone:
I tried passing nil to the selectText method, but that doesn't work:
textField.selectText(nil)
I found a number of answers on StackOverflow that mention a selectedTextRange, but this appears to be outdated, because Xcode 6.3 doesn't recognize this as a valid property on TextField.
Can anyone explain how I do this?
It's been a while since I've dealt with NSTextFields to this level (I work mostly in iOS these days).
After doing a little digging I found this on the net:
NSText* textEditor = [window fieldEditor:YES forObject:textField];
NSRange range = {start, length};
[textEditor setSelectedRange:range];
window is the window containing your field, textField.
This requires the field editor to be managing your field, what can be done simply by previously selecting the whole text of the field using the selectText:sender method.
Here is the final swift code that I got working based on what Duncan C posted:
if let window = NSApplication.sharedApplication().mainWindow {
let textEditor = window.fieldEditor(true, forObject: textField)!
let range = NSRange(0..<0)
textEditor.selectedRange = range
}

Cocoa: Activating window:shouldPopUpDocumentPathMenu:?

I have a document window with two NSWindowDelegate methods implemented in its NSDelegate:
windowWillReturnUndoManager:
window:shouldPopUpDocumentPathMenu:
The first one, windowWillReturnUndoManager, works as expected, which appears to indicate that the NSDelegate is set up correctly.
The second one, window:shouldPopUpDocumentPathMenu appears never to be called, even when command-clicking in the middle of the title bar of the window. A breakpoint set within it at "return TRUE;" never stops program operation.
Is there something else I need to do to get window:shouldPopUpDocumentPathMenu to be called?
As an alternative approach to this same issue, I downloaded the source code to TextEdit. It has the capability provided by window:shouldPopUpDocumentPathMenu—i.e. when you command-click in the title bar of a TextEdit window, you see the drop-down menu of the path to the file. But a search of the TextEdit source code for shouldPopUpDocumentPathMenu returns no results. Is window:shouldPopUpDocumentPathMenu: not required to get this functionality?
Thanks in advance to all for any info!
Best,
-Vik
Found it! All I had to do was add:
[myWindow setRepresentedURL:[self fileURL]];
... to my NSDocument's awakeFromNib method.
The document path popup now appears in the window title when the window name is command-clicked.

how to get Apple "command button" key code programmatically?

i need to know what key code of Command button in mac keyboard, do somebody know how to get it programmatically?
can i get the key code if user tap button Command + X (cut shortcut)? thank you for the suggestion
I'm going to assume here that you're dealing with NSEvents generated by the AppKit framework.
In NSEvent's documentation, take a look at the modifierFlags method.
And the flag you're lookng for is specifically the NSCommandKeyMask.
Now, to get it, if you have a NSView view in focus... it inherits from NSResponder. One of the methods in NSResponder is keyDown. So add a keyDown method to your subclassed view and the parameter it takes is a NSEvent. And that is how you would get your command button key.
BTW & FYI, if you just want to get the command key by itself (which is what I suspect), that's a bigger trick and I'm not sure if it's possible with AppKit. Because the command key, like the control and shift keys, are modifier keys and that means when events get generated, NSEvent is expecting two keys to be pressed at the same time (e.g. Command + Q for Quit, Control + C for interrupt, Shift + A for capital A).

Matlab - Send Variable From GUI to Function

I am trying to call a GUI from a function, select an item from a pop-up menu in the GUI, and pass a variable associated with the pop-up selection back to the function. The only tutorials I find on GUIs have to do with just changing things within the GUI, but not sending anything out back to a main function.
So say I have 3 options in the pop-up: Image 1, Image 2, Image 3. When for instance Image 2 is selected and the OK button is pressed, I'd like the string 'Image 2' be passed back to the main function that called the GUI.
Thanks for the help!
You can try something like: [selection, ok] = listdlg('PromptString','Select a value:', 'SelectionMode','single', 'ListString',['Value 1';'Value 2';'Value 3']). The variable selection will give you the index of the selected value.

Resources