How to catch some events on a NSControl in swift

梦想与她 提交于 2019-12-18 09:52:38

问题


I am writing an application for OSX in Swift and I am looking for a good way to catch events on a NSControl. Obviously, I searched but the informations I found are often unclear or old. In my case, I would like to catch several events on a NSTextField (key up, text changed, focus lost,...).

When I push on “Enter” in the NSTextField, it sends an action. Maybe is there a way to send an action when I click or write in the NSTextField?


回答1:


You can subclass NSTextField and override textDidChange for text change, textDidEndEditing for lost focus and keyUp method for key up. Try like this:

import Cocoa

class CustomTextField: NSTextField {
    override func viewWillMove(toSuperview newSuperview: NSView?) {
        // customize your field here
        frame = newSuperview?.frame.insetBy(dx: 50, dy: 50) ?? frame
    }
    override func textDidChange(_ notification: Notification) {
        Swift.print("textDidChange")
    }
    override func textDidEndEditing(_ notification: Notification) {
        Swift.print("textDidEndEditing")
    }
    override func keyUp(with event: NSEvent) {
        Swift.print("keyUp")
    }
}

View Controller sample Usage:


import Cocoa
class ViewController: NSViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        let textField = CustomTextField()
        view.addSubview(textField)
    }
}

Sample



来源:https://stackoverflow.com/questions/43371152/how-to-catch-some-events-on-a-nscontrol-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!