Search code examples
swiftmacoscocoaappkitnstextview

How to make a NSTextView, that is added programmatically, active?


I am making an app where a user can click anywhere on the window and a NSTextView is added at the mouse location. I have got it working with the below code but I am not able to make it active (in focus) after adding it to the view (parent view). I have to click on the NSTextView to make it active but this is not what I want. I want it to automatically become active when its added to the parent view.

Code in my ViewController to add the NSTextView to its view:

private func addText(at point: NSPoint) {     
    let textView = MyTextView(frame: NSRect(origin: point, size: CGSize(width: 150.0, height: 40.0)))
    view.addSubview(textView)       
}

MyTextView class looks like below:

class MyTextView: NSTextView {
    
    override var shouldDrawInsertionPoint: Bool {
        true
    }
    
    override var canBecomeKeyView: Bool {
        true
    }

    override func viewWillDraw() {
        
        isHorizontallyResizable = true
        isVerticallyResizable = true
        
        insertionPointColor = .red
        drawsBackground = false
        isRichText = false
        allowsUndo = true
        font = NSFont.systemFont(ofSize: 40.0)
        
    }
    
}

Also, I want it to lose focus (become inactive) when some other elements (view) are clicked. Right now, once a NSTextView becomes active, it stays active no matter what other elements I click except when I click on an empty space to create yet another NSTextView.

I have gone through the Apple docs multiple times but I think I am missing something. Any help would be much appreciated.


Solution

  • Get the NSWindow instance of the NSViewController's view and call makeFirstResponder passing the text view as parameter.

    To lose focus call makeFirstResponder passing nil.