Exploring NSTextField

NSTextField

Recently, I’m toying around NSTextField in a simple todo list application. I want to include an editable text string in each todo item. I’m writing this post to talk about things I have been applying.

Building up the project

This is a todo list, I’m going to build the basic UI using NSCollectionView. The layout is a simple row-based vertical layout. I can use NSCollectionViewFlowLayout to achieve this easily.

Displaying the todo items

Since the todo content I am going to display is quite simple, I choose a NSTextField as the container. I also link the default textField variable to the NSTextField component dropped into the item. Now I can easily display the todo by setting “textField?.stringValue”.

Callbacks in NSTextFieldDelegate

This protocol is actually an extension to NSControlTextEditingDelegate in which provides some NSControl based delegate methods which apply to text editing capability only.

The default protocol methods provide hooks to before and after editing the text content. By editing, it means typing on the keyboard in changing the content.

In fact, I want to be notified when I click on the item. Then I can modify the content and press “Return” to save the changes.

Subclassing NSTextField

In order to get notified by clicking on the item, I shall override becomeFirstResponder() in NSTextField. I also create the corresponding delegate method, so that I can make changes based on clicking the item, like showing the caret or changing the app to edit mode, etc.

Intercepting Return Key

This is done by implementing a delegate method about command selector. Each keyboard command key will generate a callback to this method. By comparing the current command selector, I am notified when “Return” key is pressed, the commandSelector is “insertNewline(_:)”. Then I can save the todo item, and change back to view mode, etc.

Summary

The working logic of NSTextField is quite different from its iOS counterpart, UITextField. The documentation for NSTextField delegate is quite ambiguous. One should be more careful and toy around those callbacks before implementing your logic of desire.


I am taking a challenge to write a post every day for 180 days. The content will be related to my life as a father, entrepreneur, developer and trainer.

Recent articles:

Show your support

Clapping shows how much you appreciated Harry Ng’s story.