swiftmacoscocoanstextfieldforce-touch

NSTextField - Allow editing only with force-touch, Cocoa


I am developing a OSX app with Force touch support.

As default, if you set an NSTextField's behaviour editable, user can click two times or use force touch to start editing.

I want to allow user start editing only with Force touch. How can I handle this?


Solution

  • Subclass NSTextField and override pressureChange(with:). Then, check event.stage for the level of the pressure (or event.pressure for the accurate value). If event.stage is 2, it is the force touch.

    @available(macOS 10.10.3, *)
    override func pressureChange(with event: NSEvent) {
    
        if event.stage == 2, !self.isEditable {
            self.isEditable = true
            self.selectText(self)
        }
    }