Execute callback when text changes inside a NSTextField in Swift - macos

I have a NSTextField and I would like to execute a callback whenever the text inside it changes. The callback would be to enable a disabled "save" button at the bottom of the form.
What I managed to do so far is sub-class NSTextView in order to override textDidChange(notification)
import Cocoa
class MyTextField: NSTextField {
override func textDidChange(notification: NSNotification) {
super.textDidChange(notification)
}
}
After that, I didn't manage to execute a function inside my ViewController. I tried using NSNotificationCenter to trigger some kind of global event that I could catch inside the ViewController like so :
//MyTextField.swift
import Cocoa
class MyTextField: NSTextField {
override func textDidChange(notification: NSNotification) {
NSNotificationCenter.defaultCenter().postNotification(notification)
super.textDidChange(notification)
}
}
//ViewController.swift
import Cocoa
class ViewController: NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "fieldTextDidChange:", name: "NSTextDidChangeNotification", object: nil)
}
override func viewDidAppear() {
super.viewDidAppear()
}
func fieldTextDidChange(notification: NSNotification) {
print(notification, appendNewline: true)
}
}
But I get a runtime error when typing inside the field : Thread 1: EXC_BAD_ACCESS (code=2, address=0x7fff5f3fff70) on the line that calls postNotification()
How can I manage to trigger a callback on text change of a NSTextField ?
EDIT
Sub-classing and sending a notification is silly as pointed out by matt. There is no need to sub-class the text field. Simply observing the NSTextDidChangeNotification is enough to react to the event I was looking for.
I had tested this but I was missing a colon at the end of the selector on top of this, so I thought it was not the correct method. It is indeed the correct method.

The reason you are crashing is that your selector is wrong. It should be selector: "fieldTextDidChange:" (notice the final colon).

Related

How to clear NSTextView selection without it becoming first responder?

I have a basic Cocoa app with a number of NSTextViews. When a text view loses focus (i.e. resigns its first responder status), I'd like to clear its selection.
My strategy was to extend NSTextView and override resignFirstResponder():
override func resignFirstResponder() -> Bool {
// Both result in the text view becoming first responder again:
clearSelection(nil)
setSelectedRange(NSRange(location: 0, length: 0))
return super.resignFirstResponder()
}
The problem is that calling clearSelection() and setSelectedRange() both cause the text view to become first responder again.
Is there a way to clear the selection without it becoming the first responder?
I tried to also override acceptsFirstResponder and temporarily return false, but that didn't work either.
Met the same issue today and found the solution
You can do setSelectedRange in NSTextView's delegate method textDidEndEditing and it wouldn't cause NSTextView become first responder.
class TextView: NSTextView {
init() {
self.delegate = self
....
}
....
}
extension TextView: NSTextViewDelegate {
public func textDidEndEditing(_ notification: Notification) {
setSelectedRange(NSMakeRange(string.count, 0))
}
}

NSWindow opens but buttons doesn't work and I cannot create IBOutlets

I have the following NSWindowController:
import Foundation
import Cocoa
extension NSImage.Name {
static let skyflokLogo = NSImage.Name("skyflokLogo")
}
class LoginWindowController: NSWindowController {
override func windowDidLoad() {
super.windowDidLoad()
}
#IBAction func cancelLogin(_ sender: NSButton) {
print("Jones")
}
#IBAction func confirmLogin(_ sender: NSButton) {
print("lol")
}
}
and I open the window like this:
static func loadLoginWindow() -> NSWindowController {
let win = LoginWindowController(windowNibName: NSNib.Name("LoginWindow"))
win.showWindow(self)
return win
}
And store it in the AppDelegate class:
#IBAction func loginFunction(_ sender: NSMenuItem) {
print("TEST")
testCtrl = UIHelpers.loadLoginWindow()
}
And components the window contains can be seen here:
My problem is that the window opens as it is supposed to, but my IBAction functions does not work and I cannot create IBOutlets by control dragging from the window. Can someone direct me to documentation or help me solve this?
You need to hold your LoginWindow (I personally recommend to append "Controller" to the class name) instance somewhere. Otherwise, the instance disappears as soon as loadLoginWindow() ended, and therefore IBActions cannot be performed.

NSResponder accepts events when acceptsFirstResponder is false?

Why are the methods moveLeft() and moveRight() being called, I have turned off the first responder ability for the window controller? I haven't added any code in elsewhere, so I'm obviously missing something somewhere...
In the end I do want to accept events, but if I 'enable' them here and deal with overriding keyEvent(), it causes it to be handled twice and a choice being made twice.
import Cocoa
enum UserChoice {
case Left, Right
}
class MainWindowController: NSWindowController {
override func windowDidLoad() {
super.windowDidLoad()
}
override var windowNibName: String? {
return "MainWindowController"
}
override var acceptsFirstResponder: Bool {
return false
}
override func moveLeft(sender: AnyObject?) {
chooseImage(UserChoice.Left)
}
override func moveRight(sender: AnyObject?) {
chooseImage(UserChoice.Right)
}
func chooseImage(choice: UserChoice) {
print("choice made")
}
}
The only other file I have is AppDelegate.swift:
import Cocoa
#NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
var mainWindowController: MainWindowController!
func applicationDidFinishLaunching(notification: NSNotification) {
mainWindowController = MainWindowController()
mainWindowController.showWindow(self)
}
}
Any comments on my code are welcome too, I'm new to Swift/Cocoa so...
When your controller refuses to be first responder, it's still a responder, just not the first one. Another responder such as the window or a view within it can choose to pass the buck back up the responder chain.
I'm not clear on why you implemented moveLeft and moveRight if you don't want to handle them.

Add completion handler to presentViewControllerAsSheet(NSViewController)?

I am attempting to present a sheet configuration view (AddSoundEffect) for my main window/view controller (I'm using storyboards), and when the configuration view controller is dismissed, take the values entered in the AddSoundEffect view and pass that back to the main view. My current code in the main view controller:
presentViewControllerAsSheet(self.storyboard!.instantiateControllerWithIdentifier("AddSoundEffect") as! AddSoundViewController
And in the AddSoundViewController.swift file, the code to dismiss it is:
self.dismissViewController(self)
To pass the data, I have a class-independent tuple that I save data to. How do I add a completion handler to presentViewControllerAsSheet, and (optionally) is there a better way to pass the data between view controllers?
Setup: Xcode version 6.4, OS X 10.10.4
Delegation pattern is the easiest way for you.
// Replace this with your tuple or whatever data represents your sound effect
struct SoundEffect {}
protocol AddSoundViewControllerDelegate: class {
func soundViewController(controller: AddSoundViewController, didAddSoundEffect: SoundEffect)
}
//
// Let's say this controller is a modal view controller for adding new sound effects
//
class AddSoundViewController: UIViewController {
weak var delegate: AddSoundViewControllerDelegate?
func done(sender: AnyObject) {
// Dummy sound effect info, replace it with your own data
let soundEffect = SoundEffect()
//
// Call it whenever you would like to inform presenting view controller
// about added sound effect (in case of Done, Add, ... button tapped, do not call it
// when user taps on Cancel to just dismiss AddSoundViewController)
//
self.delegate?.soundViewController(self, didAddSoundEffect: soundEffect)
// Dismiss self
self.dismissViewControllerAnimated(true, completion: {})
}
}
//
// Let's say this controller is main view controller, which contains list of all sound effects,
// with button to add new sound effect via AddSoundViewController
//
class SoundEffectsViewController: UIViewController, AddSoundViewControllerDelegate {
func presentAddSoundEffectController(sender: AnyObject) {
if let addSoundController = self.storyboard?.instantiateViewControllerWithIdentifier("AddSoundEffect") as? AddSoundViewController {
addSoundController.delegate = self
self.presentViewController(addSoundController, animated: true, completion: {})
}
}
func soundViewController(controller: AddSoundViewController, didAddSoundEffect: SoundEffect) {
// This method is called only when new sound effect is added
}
}
Another way is to use closures:
// Replace this with your tuple or whatever data represents your sound effect
struct SoundEffect {}
//
// Let's say this controller is a modal view controller for adding new sound effects
//
class AddSoundViewController: UIViewController {
var completionHandler: ((SoundEffect) -> ())?
func done(sender: AnyObject) {
// Dummy sound effect info, replace it with your own data
let soundEffect = SoundEffect()
//
// Call it whenever you would like to inform presenting view controller
// about added sound effect (in case of Done, Add, ... button tapped, do not call it
// when user taps on Cancel to just dismiss AddSoundViewController)
//
self.completionHandler?(soundEffect)
// Dismiss self
self.dismissViewControllerAnimated(true, completion: {})
}
}
//
// Let's say this controller is main view controller, which contains list of all sound effects,
// with button to add new sound effect via AddSoundViewController
//
class SoundEffectsViewController: UIViewController {
func presentAddSoundEffectController(sender: AnyObject) {
if let addSoundController = self.storyboard?.instantiateViewControllerWithIdentifier("AddSoundEffect") as? AddSoundViewController {
addSoundController.completionHandler = { [weak self] (soundEffect) -> () in
// Called when new sound effect is added
}
self.presentViewController(addSoundController, animated: true, completion: {})
}
}
}
Or many other ways like sending notification, ... Whatever suits your needs. But delegation pattern or closures is the best way to go in this specific case.
I missed that your question is about NSViewController. This example is for iOS, but same pattern can be used on OS X without any issues.
The easiest way to detect sheet opening or closing is to use the Sheet Notifications:
class ViewController: NSViewController, NSWindowDelegate {
override func viewDidLoad(){
NSApplication.sharedApplication().windows.first?.delegate = self
}
func windowDidEndSheet(notification: NSNotification) {
}
func windowWillBeginSheet(notification: NSNotification) {
}
}

Move a NSWindow by dragging a NSView

I have a NSWindow, on which i apply this:
window.styleMask = window.styleMask | NSFullSizeContentViewWindowMask
window.titleVisibility = NSWindowTitleVisibility.Hidden;
window.titlebarAppearsTransparent = true;
I then add a NSView behind the titlebar to simulate a bigger one.
Now it looks like this:
I want to be able to move the window, by dragging the light-blue view. I have already tried to subclass NSView and always returning true for mouseDownCanMoveWindow using this code:
class LSViewD: NSView {
override var mouseDownCanMoveWindow:Bool {
get {
return true
}
}
}
This didn't work.
After some googling i found this INAppStoreWindow on GitHub. However it doesn't support OS X versions over 10.9, so it's completely useless for me.
Edit1
This is how it looks in the Interface Builder.
How can i move the window, by dragging on this NSView?
None of the answers here worked for me. They all either don't work at all, or make the whole window draggable (note that OP is not asking for this).
Here's how to actually achieve this:
To make a NSView control the window with it's drag events, simply subclass it and override the mouseDown as such:
class WindowDragView: NSView {
override public func mouseDown(with event: NSEvent) {
window?.performDrag(with: event)
}
}
That's it. The mouseDown function will transfer further event tracking to it's parent window.
No need for window masks, isMovableByWindowBackground or mouseDownCanMoveWindow.
Try setting the window's movableByWindowBackground property to true.
There are two ways to do this. The first one would be to set the NSTexturedBackgroundWindowMask as well as the windows background color to the one of your view. This should work.
Otherwise you can take a look at this Sample Code
I somehow managed to solve my problem, i don't really know how, but here are some screenshots.
In the AppDelegate file where i edit the properties of my window, i added an IBOutlet of my contentView. This IBOutlet is a subclass of NSView, in which i've overriden the variable mouseDownCanMoveWindow so it always returns false.
I tried this before in only one file, but it didn't work. This however solved the problem.
Thanks to Ken Thomases and Max for leading me into the right direction.
Swift3.0 Version
override func viewDidAppear() {
//for hide the TitleBar
self.view.window?.styleMask = .borderless
self.view.window?.titlebarAppearsTransparent = true
self.view.window?.titleVisibility = .hidden
//for Window movable with NSView
self.view.window?.isMovableByWindowBackground = true
}
Swift 3:
I needed this but dynamically. It's a little long but well worth it (IMHO).
So I decided to enable this only while the command key is down. This is achieved by registering a local key handler in the delegate:
// MARK:- Local key monitor
var localKeyDownMonitor : Any? = nil
var commandKeyDown : Bool = false {
didSet {
let notif = Notification(name: Notification.Name(rawValue: "commandKeyDown"),
object: NSNumber(booleanLiteral: commandKeyDown))
NotificationCenter.default.post(notif)
}
}
func keyDownMonitor(event: NSEvent) -> Bool {
switch event.modifierFlags.intersection(.deviceIndependentFlagsMask) {
case [.command]:
self.commandKeyDown = true
return true
default:
self.commandKeyDown = false
return false
}
}
which is enabled within the delegate startup:
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Watch local keys for window movenment, etc.
localKeyDownMonitor = NSEvent.addLocalMonitorForEvents(matching: NSEventMask.flagsChanged) { (event) -> NSEvent? in
return self.keyDownMonitor(event: event) ? nil : event
}
}
and its removal
func applicationWillTerminate(_ aNotification: Notification) {
// Forget key down monitoring
NSEvent.removeMonitor(localKeyDownMonitor!)
}
Note that when the commandKeyDown value is changed by the key down handler. This value change is caught by the didset{} to post a notification. This notification is registered by any view you wish to have its window so moved - i.e., in the view delegate
override func viewDidLoad() {
super.viewDidLoad()
// Watch command key changes
NotificationCenter.default.addObserver(
self,
selector: #selector(ViewController.commandKeyDown(_:)),
name: NSNotification.Name(rawValue: "commandKeyDown"),
object: nil)
}
and discarded when the viewWillDisappear() (delegate) or the window controller windowShouldClose(); add this
<your-view>.removeObserver(self, forKeyPath: "commandKeyDown")
So sequence goes like this:
key pressed/release
handler called
notification posted
The view's window isMovableByWindowBackground property is changed by notification - placed within view controller / delegate or where you registered the observer.
internal func commandKeyDown(_ notification : Notification) {
let commandKeyDown : NSNumber = notification.object as! NSNumber
if let window = self.view.window {
window.isMovableByWindowBackground = commandKeyDown.boolValue
Swift.print(String(format: "command %#", commandKeyDown.boolValue ? "v" : "^"))
}
}
Remove the tracer output when happy. See it in action in SimpleViewer on github.

Resources