How to be equal to all keyCodes - cocoa

I would like for the event.keyCode to be equal to all the keyCodes
but right now i can only make it be equal to one shown below
override func keyDown(with event: NSEvent) {
if event.keyCode == 1 {
textField1.stringValue = "anything"
}
}
Thanks!

If you just want to do something on every key down, simply don't check the key code at all:
override func keyDown(with event: NSEvent) {
textField1.stringValue = "anything"
}

Related

Detecting arrow/enter keys when editing NSTextField

I couldn't find anything up to date that solve this issue.
How can I monitor something like arrow key presses while editing an NSTextField?
From what I looked up:
- NSControlTextEditingDelegate functions are not called (and I wouldn't know how to use them)
- NSTextFieldDelegate functions don't list something that would work here
Set your text field's delegate:
textField.delegate = self
Add the following inheritance for protocols:
class MyTextField : NSTextFieldDelegate, NSControlTextEditingDelegate { ...
And implement the following:
func control(_ control: NSControl, textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {
if commandSelector == #selector(moveUp(_:)) {
...
} else if commandSelector == #selector(moveDown(_:)) {
...
} else if commandSelector == #selector(insertNewline(_:)) {
...
}
return true
}
There are more in depth explanations in this link Recognize if user has pressed arrow key while editing NSTextField swift
keyDown doesn't seem to work with NSTextFields (it does for NSTextView), so what I did on my side was subclass either NSTextField or ViewController and add these methods:
import Cocoa
class MyTextField: NSTextField
{
override func keyUp(with event: NSEvent) {
print("MyTextField keyUp key is %ld", event.keyCode)
super.keyUp(with: event)
}
}
class MyTextView: NSTextView
{
override func keyDown(with event: NSEvent) {
print("MyTextView keyDown key is %ld", event.keyCode)
super.keyDown(with: event)
}
}
class ViewController: NSViewController {
override func keyUp(with event: NSEvent) {
print("ViewController keyUp key is %ld", event.keyCode)
super.keyUp(with: event)
}
}

NSView does not receive mouseUp: event when mouse button is released outside of view

I have a custom NSView subclass with (for example) the following methods:
override func mouseDown(with event: NSEvent) { Swift.print("mouseDown") }
override func mouseDragged(with event: NSEvent) { Swift.print("mouseDragged") }
override func mouseUp(with event: NSEvent) { Swift.print("mouseUp") }
As long as the mouse (button) is pressed, dragged and released all inside the view, this works fine. However, when the mouse is depressed inside the view, moved outside the view, and only then released, I never receive the mouseUp event.
P.S.: Calling the super implementations does not help.
The Handling Mouse Dragging Operations section of Apple's mouse events documentation provided a solution: Apparently, we do receive the mouseUp event when tracking events with a mouse-tracking loop.
Here's a variant of the sample code from the documentation, adapted for Swift 3:
override func mouseDown(with event: NSEvent) {
var keepOn = true
mouseDownImpl(with: event)
// We need to use a mouse-tracking loop as otherwise mouseUp events are not delivered when the mouse button is
// released outside the view.
while true {
guard let nextEvent = self.window?.nextEvent(matching: [.leftMouseUp, .leftMouseDragged]) else { continue }
let mouseLocation = self.convert(nextEvent.locationInWindow, from: nil)
let isInside = self.bounds.contains(mouseLocation)
switch nextEvent.type {
case .leftMouseDragged:
if isInside {
mouseDraggedImpl(with: nextEvent)
}
case .leftMouseUp:
mouseUpImpl(with: nextEvent)
return
default: break
}
}
}
func mouseDownImpl(with event: NSEvent) { Swift.print("mouseDown") }
func mouseDraggedImpl(with event: NSEvent) { Swift.print("mouseDragged") }
func mouseUpImpl(with event: NSEvent) { Swift.print("mouseUp") }
Am posting this as an answer to a similar question that I had where I needed to know that the user had stopped using a slider. I needed to capture the mouseUp event from NSSlider or actually NSView. The solution that worked out for me was to simply capture the mouseDown event and add some code when it exited and does the job that I needed. Hope that this is of use to somebody else who needs to do a similar thing. Code written using XCode 11.3.1 Swift 5
import Cocoa
class SMSlider: NSSlider {
var calledOnExit:(()->())?
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
}
override func mouseDown(with event: NSEvent) {
super.mouseDown(with: event)
if self.calledOnExit != nil {
self.calledOnExit!()
}
}
}
// In my main swift app
func sliderStopped() {
print("Slider stopped moving")
}
//...
if slider == nil {
slider = SMSlider()
}
slider?.isContinuous = true
slider?.target = self
slider?.calledOnExit = sliderStopped
//...

Cocoa: react to keyDown in QLPreviewPanel

I implemented quick look in my project in the following way in Swift 2 (I'm including this here for reference and because it might help someone else set it up).
My NSViewController contains a NSTableView subclass where I implemented keyDown to listen to the spacebar key being pressed (maybe not the best way but it works):
override func keyDown(theEvent: NSEvent) {
let s = theEvent.charactersIgnoringModifiers!
let s1 = s.unicodeScalars
let s2 = s1[s1.startIndex].value
let s3 = Int(s2)
if s3 == Int(" ".utf16.first!) {
NSNotificationCenter.defaultCenter().postNotification(NSNotification(name: "MyTableViewSpacebar", object: nil))
return
}
super.keyDown(theEvent)
}
In my view controller, I have an observer for this notification and the functions required by the QLPreviewPanel:
//...
class ViewController: NSViewController {
#IBOutlet weak var myTableView: MyTableView!
var files = [FilesListData]() //array of custom class
//...
override func viewDidLoad() {
//...
NSNotificationCenter.defaultCenter().addObserver(self, selector: "spaceBarKeyDown:", name: "MyTableViewSpacebar", object: nil)
}
func spaceBarKeyDown(notification: NSNotification) {
if let panel = QLPreviewPanel.sharedPreviewPanel() {
panel.makeKeyAndOrderFront(self)
}
}
override func acceptsPreviewPanelControl(panel: QLPreviewPanel!) -> Bool {
return true
}
override func beginPreviewPanelControl(panel: QLPreviewPanel!) {
panel.delegate = self
panel.dataSource = self
}
override func endPreviewPanelControl(panel: QLPreviewPanel!) {
}
}
extension ViewController: QLPreviewPanelDataSource {
func numberOfPreviewItemsInPreviewPanel(panel: QLPreviewPanel!) -> Int {
return self.myTableView.selectedRowIndexes.count
}
func previewPanel(panel: QLPreviewPanel!, previewItemAtIndex index: Int) -> QLPreviewItem! {
if self.myTableView.selectedRow != -1 {
var items = [QLPreviewItem]()
let manager = NSFileManager.defaultManager()
for i in self.myTableView.selectedRowIndexes {
let path = self.files[i].path //path to a MP3 file
if manager.fileExistsAtPath(path) {
items.append(NSURL(fileURLWithPath: path))
} else {
items.append(qm_url) //image of a question mark used as placeholder
}
}
return items[index]
} else {
return qm_url //image of a question mark used as placeholder
}
}
}
What I would like to do now is listen to the keys "up arrow" and "down arrow" being pressed while the quick look panel is open, in order to change the selected row in the NSTableView, much like Finder behaves when you preview files with quick look. I have no clue as to how I could implement this. Any ideas?
Thanks.
Finally found what I was looking for and it's actually pretty simple.
Since my main view controller is also my delegate for the QLPreviewPanel, I added this:
extension ViewController: QLPreviewPanelDelegate {
func previewPanel(panel: QLPreviewPanel!, handleEvent event: NSEvent!) -> Bool {
let kc = event.keyCode
if (kc == 126 || kc == 125) { //up and down arrows
if event.type == NSEventType.KeyDown {
self.myTableView.keyDown(event) //send the event to the table
} else if event.type == NSEventType.KeyUp {
self.myTableView.keyUp(event)
}
return true
}
return false
}
}
Then in my table view delegate:
func tableViewSelectionDidChange(notification: NSNotification) {
guard myTableView.numberOfSelectedRows > 0 else {
if let panel = QLPreviewPanel.sharedPreviewPanel() {
if panel.visible {
panel.close()
}
}
return
}
if let panel = QLPreviewPanel.sharedPreviewPanel() {
if panel.visible {
panel.reloadData()
}
}
}
That's it! The QLPreviewPanelDataSource handles the rest.

Swift - Capture keydown from NSViewController

I would like to capture keyevents in my little app.
What I have done:
class ViewController : NSViewController {
...
override func keyDown(theEvent: NSEvent) {
if theEvent.keyCode == 124 {
println("abc")
} else {
println("abcd")
}
}
override var acceptsFirstResponder: Bool {
return true
}
override func becomeFirstResponder() -> Bool {
return true
}
override func resignFirstResponder() -> Bool {
return true
}
...
}
What happens:
When a key pressed, the Funk sound effect plays.
I've seen many posts talking about how this is a delegate the belongs to NSView and NSViewController does not have access. But the keydown function override auto completes in a class of type NSViewController leading me to believe that this is wrong.
Xcode 8.2.1 • Swift 3.0.2
import Cocoa
class ViewController: NSViewController {
#IBOutlet var textField: NSTextField!
override func viewDidLoad() {
super.viewDidLoad()
NSEvent.addLocalMonitorForEvents(matching: .flagsChanged) {
self.flagsChanged(with: $0)
return $0
}
NSEvent.addLocalMonitorForEvents(matching: .keyDown) {
self.keyDown(with: $0)
return $0
}
}
override func keyDown(with event: NSEvent) {
switch event.modifierFlags.intersection(.deviceIndependentFlagsMask) {
case [.command] where event.characters == "l",
[.command, .shift] where event.characters == "l":
print("command-l or command-shift-l")
default:
break
}
textField.stringValue = "key = " + (event.charactersIgnoringModifiers
?? "")
textField.stringValue += "\ncharacter = " + (event.characters ?? "")
}
override func flagsChanged(with event: NSEvent) {
switch event.modifierFlags.intersection(.deviceIndependentFlagsMask) {
case [.shift]:
print("shift key is pressed")
case [.control]:
print("control key is pressed")
case [.option] :
print("option key is pressed")
case [.command]:
print("Command key is pressed")
case [.control, .shift]:
print("control-shift keys are pressed")
case [.option, .shift]:
print("option-shift keys are pressed")
case [.command, .shift]:
print("command-shift keys are pressed")
case [.control, .option]:
print("control-option keys are pressed")
case [.control, .command]:
print("control-command keys are pressed")
case [.option, .command]:
print("option-command keys are pressed")
case [.shift, .control, .option]:
print("shift-control-option keys are pressed")
case [.shift, .control, .command]:
print("shift-control-command keys are pressed")
case [.control, .option, .command]:
print("control-option-command keys are pressed")
case [.shift, .command, .option]:
print("shift-command-option keys are pressed")
case [.shift, .control, .option, .command]:
print("shift-control-option-command keys are pressed")
default:
print("no modifier keys are pressed")
}
}
}
To get rid of the purr sound when pressing the character keys you need to subclass your view, override the method performKeyEquivalent and return true.
import Cocoa
class View: NSView {
override func performKeyEquivalent(with event: NSEvent) -> Bool {
return true
}
}
Sample Project
Swift4
Just found a solution for the very same problem, Swift4. The idea behind that: if the pressed key was handled by a custom logic, the handler shall return nil, otherwise the (unhandled) event...
class MyViewController: NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
// ...
NSEvent.addLocalMonitorForEvents(matching: .keyDown) {
if self.myKeyDown(with: $0) {
return nil
} else {
return $0
}
}
}
func myKeyDown(with event: NSEvent) -> Bool {
// handle keyDown only if current window has focus, i.e. is keyWindow
guard let locWindow = self.view.window,
NSApplication.shared.keyWindow === locWindow else { return false }
switch Int( event.keyCode) {
case kVK_Escape:
// do what you want to do at "Escape"
return true
default:
return false
}
}
}
And here we are: no Purr / Funk sound when key is pressed...
[Update] Added check of keyWindow. Without this, keyDown() is fired even if another view/window contains the first responder...
I was trying to find an answer for swift 3, here is what worked for me:
Swift 3
import Cocoa
// We subclass an NSView
class MainView: NSView {
// Allow view to receive keypress (remove the purr sound)
override var acceptsFirstResponder : Bool {
return true
}
// Override the NSView keydown func to read keycode of pressed key
override func keyDown(with theEvent: NSEvent) {
Swift.print(theEvent.keyCode)
}
}
I manage to get it work from subclass of NSWindowController
class MyWindowController: NSWindowController {
override func keyDown(theEvent: NSEvent) {
print("keyCode is \(theEvent.keyCode)")
}
}
UPDATE:
import Cocoa
protocol WindowControllerDelegate {
func keyDown(aEvent: NSEvent)
}
class WindowController: NSWindowController {
var delegate: WindowControllerDelegate?
override func windowDidLoad() {
super.windowDidLoad()
delegate = window?.contentViewController as! ViewController
}
override func keyDown(theEvent: NSEvent) {
delegate?.keyDown(theEvent)
}
}
and ViewController:
class ViewController: NSViewController, WindowControllerDelegate {
#IBOutlet weak var textField: NSTextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override var representedObject: AnyObject? {
didSet {
// Update the view, if already loaded.
}
}
override func keyDown(theEvent: NSEvent) {
textField.stringValue = "key = " + (theEvent.charactersIgnoringModifiers
?? "")
textField.stringValue += "\ncharacter = " + (theEvent.characters ?? "")
textField.stringValue += "\nmodifier = " + theEvent.modifierFlags.rawValue.description
}
}
let kLeftArrowKeyCode: UInt16 = 123
let kRightArrowKeyCode: UInt16 = 124
let kDownArrowKeyCode: UInt16 = 125
let kUpArrowKeyCode: UInt16 = 126
override func keyDown(with event: NSEvent) {
switch event.keyCode {
case kLeftArrowKeyCode:
print("left")
break
case kRightArrowKeyCode:
print("right")
break
case kDownArrowKeyCode:
print("down")
break
case kUpArrowKeyCode:
print("up")
break
default:
print("other")
super.keyDown(with: event)
break
}
print("Key with number: \(event.keyCode) was pressed")
}

How to get the pressed keys in Swift

I am trying to learn the Swift language, and I followed a lot of tutorials on Youtube. Since most of them are for iOS, I wanted to make the OSX version of this one: https://www.youtube.com/watch?v=8PrVHrs10to (SideScroller game)
I followed it carefully but I am stuck at about 22 minutes of the video when I have to update the player position. My first problem was to get the pressed keys. I come from C# language, so I wanted to find something like
If(Keyboard.GetState().IsKeyDown(Keys.Right))
man.Position.x += 5 //player position
but this doesn't exist, so I figured out this:
override func keyDown(theEvent: NSEvent!)
{
updateManPosition(theEvent)
}
func updateManPosition(theEvent:NSEvent)
{
if theEvent.keyCode == 123
{
man.position.x -= 2
}
else if theEvent.keyCode == 124
{
man.position.x += 2
}
else if theEvent.keyCode == 126
{
println("jump")
}
}
I found the corresponding value(123/124/126) by using println(theEvent.keyCode) but it's not very useful if I have to recognize a lot of keys.
Anyway, it works for this game, the position of the player changes. But I have another probem which is that the function keyDown doesn't seem to be called at each update (so 60 times per seconds) which prevent the player to move smoothly.
SO, here is my question: How can I have keyDown called at each update, and does anybody have a cleaner way to get the pressed Keys ?
Thank you
Okay I found how to update, so I post it here 'cause it might help others. The idea is to use a boolean:
var manIsMoving:Bool = false
override func keyDown(theEvent: NSEvent!) // A key is pressed
{
if theEvent.keyCode == 123
{
direction = "left" //get the pressed key
}
else if theEvent.keyCode == 124
{
direction = "right" //get the pressed key
}
else if theEvent.keyCode == 126
{
println("jump")
}
manIsMoving = true //setting the boolean to true
}
override func keyUp(theEvent: NSEvent!)
{
manIsMoving = false
}
override func update(currentTime: CFTimeInterval)
{
if manIsMoving
{
updateManPosition(direction)
}
else
{
cancelMovement()
}
}
It may help others.
But getting the pressed key's characters is still unclear...
In combination with the above method I have created a method to change a key to a character:
private func returnChar(theEvent: NSEvent) -> Character?{
let s: String = theEvent.characters!
for char in s{
return char
}
return nil
}
This will return a character (from the key that was pressed).
Then you can do something like this:
override func keyUp(theEvent: NSEvent) {
let s: String = String(self.returnChar(theEvent)!)
switch(s){
case "w":
println("w")
break
case "s":
println("s")
break
case "d":
println("d")
break
case "a":
println("a")
break
default:
println("default")
}
}
You could combine this method and the method from above to create something like a key listener.

Resources