MacOS 용 Swift에 코드를 쓰고 있습니다. (UIkit을 사용하지 않고 AppKit을 사용하고 있습니다). 편집 할 수없는 NSTextView가 있습니다. 터미널 유형을 모방하고 싶습니다. 아래 코드는 사용자가 RETURN을 누르고 ">> \ n"을 인쇄 할 때 이해합니다. 나는 해당 키를 작성하기 위해 사용자가 아무 키나 누를 때 통보받을 수 있기를 원합니다. 예를 들어 사용자가 백 스페이스 키를 누르면 ">>"가 삭제되지 않는 한 NSTextView에서 한 문자를 삭제합니다.NSTextView에서 키 누름 이벤트 (macOS)
이것은 코드입니다. 수입 코코아
class ViewController: NSViewController {
@IBOutlet var console: Console!
override func viewDidLoad() {
super.viewDidLoad()
console.parent = self
}
func newLine() {
let textStorage = console.textStorage
if(textStorage != nil) {
let myString = "\n>>"
let myAttribute = [ NSForegroundColorAttributeName: NSColor.greenColor(), NSFontAttributeName: NSFont(name: "Menlo Regular", size: 13.0)! ]
let myAttrString = NSAttributedString(string: myString, attributes: myAttribute)
textStorage!.appendAttributedString(myAttrString)
let length = console.string!.characters.count
console.setSelectedRange(NSRange(location: length,length: 0))
console.scrollRangeToVisible(NSRange(location: length,length: 0))
}
}
override var representedObject: AnyObject? {
didSet {
// Update the view, if already loaded.
}
}
}
class Console : NSTextView {
var parent: ViewController?
override func insertNewline(sender: AnyObject?) {
parent!.newLine()
}
override func controlTextDidBeginEditing(obj: NSNotification) {
NSLog("wow") //unfortunately this method is never called, even setting the NSTextView as Editable
}
}
관련 질문 : How to capture user input in real time in NSTextField?
고맙습니다. 시도해 보겠습니다. – Nisba
완벽하게 작동합니다. – Nisba