我在Swift 5中有一个小型的macOS应用程序。这是一个简单的计算器,单行显示为NSTextField
。您在此处输入数学expression
(例如:“ 34 * 12”),然后按Enter键,然后从String
中得到结果-出现在同一NSTextField
中。这样,用户就可以继续进行计算-只需在结果的后面前面输入,然后再次按Enter键即可。
我从字面上搜索了几天,找不到能防止NSTextField
在按下Enter键后突出显示其内容的解决方案。
不幸的是,由于我根本不知道从哪里开始,所以我没有太多代码要显示。
self.fileTextField.currentEditor()?.moveToEndOfDocument(nil)
只是不执行任何操作,而其他的“解决方法”则是诸如假按向右箭头键导致macOS中的权限问题:
let rightArrowKeyCode: UInt16 = 124
let keyDownEvent = CGEvent(keyboardEventSource: nil, virtualKey: rightArrowKeyCode, keyDown: true)
keyDownEvent?.flags = CGEventFlags.maskCommand
keyDownEvent?.post(tap: CGEventTapLocation.cghidEventTap)
let keyUpEvent = CGEvent(keyboardEventSource: nil, virtualKey: rightArrowKeyCode, keyDown: false)
keyUpEvent?.flags = CGEventFlags.maskCommand
keyUpEvent?.post(tap: CGEventTapLocation.cghidEventTap)
代码简短(使用Expression框架):
@IBOutlet weak var calcLine: NSTextField!
@IBAction func runCalc(_ sender: NSTextField) {
let stringValue = calcLine.stringValue
let expression = Expression(calcLine.stringValue)
do {
result = try expression.evaluate()
currentResult = result
calcLine.stringValue = "\(result)"
} catch {
print("\(error)")
}
}
我尝试了很多在这里发现的东西,但是它们看起来很老,我才刚刚开始为macOS应用学习Swift。