[英]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.我正在制作一个应用程序,用户可以在其中单击 window 上的任何位置,并在鼠标位置添加
NSTextView
。 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.我必须单击
NSTextView
使其处于活动状态,但这不是我想要的。 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:我的
ViewController
中的代码将NSTextView
添加到其视图中:
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: MyTextView
class 如下所示:
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
.现在,一旦
NSTextView
变为活动状态,无论我单击什么其他元素,它都会保持活动状态,除非我单击空白空间以创建另一个NSTextView
。
I have gone through the Apple docs multiple times but I think I am missing something.我已经多次阅读 Apple 文档,但我认为我遗漏了一些东西。 Any help would be much appreciated.
任何帮助将非常感激。
Get the NSWindow
instance of the NSViewController
's view
and call makeFirstResponder
passing the text view as parameter.获取
NSViewController
view
的NSWindow
实例并调用makeFirstResponder
,将文本视图作为参数传递。
To lose focus call makeFirstResponder
passing nil
.失去焦点调用
makeFirstResponder
传递nil
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.