我在使用Swift-4的MacOS应用程序上有一个NSTextField
其目的是让用户输入一个数字。 有没有办法根据向上滚动或向下滚动鼠标滚轮来更改数字?
答案 0 :(得分:3)
您可以覆盖scrollWheel(with event: NSEvent)
方法并检查event.deltaY
是正还是负,并增加或减少textField值:
import Cocoa
class ViewController: NSViewController {
@IBOutlet weak var textField: NSTextField!
override func viewDidLoad() {
super.viewDidLoad()
textField.stringValue = "0"
}
override func scrollWheel(with event: NSEvent) {
super.scrollWheel(with: event)
if var value = Int(textField.stringValue) {
if event.deltaY > 0 {
value += 1
}
if event.deltaY < 0 {
value -= 1
}
textField.stringValue = String(value)
print(value)
}
}
}
如果您只想更改具有焦点的字段,可以使用视图窗口fieldEditor:
if let text = view.window?.fieldEditor(false, for: nil) {
if var value = Int(text.string) {
if event.deltaY > 0 {
value += 1
}
if event.deltaY < 0 {
value -= 1
}
text.string = String(value)
print(value)
}
}
如果您想将滚动限制为仅特定字段,则需要将视图控制器设置为其委托,并将其委托与textfield对象进行比较:
import Cocoa
class ViewController: NSViewController, NSTextFieldDelegate {
@IBOutlet weak var textField1: NSTextField!
@IBOutlet weak var textField2: NSTextField!
override func viewDidAppear() {
super.viewDidAppear()
textField1.delegate = self
}
override func viewDidLoad() {
super.viewDidLoad()
textField1.stringValue = "0"
textField2.stringValue = "0"
}
override func scrollWheel(with event: NSEvent) {
super.scrollWheel(with: event)
if let textField = (view.window?.firstResponder as? NSTextView)?.delegate, textField === textField1 {
if let text = view.window?.fieldEditor(false, for: nil) {
if var value = Int(text.string) {
if event.deltaY > 0 {
value += 1
}
if event.deltaY < 0 {
value -= 1
}
text.string = String(value)
print(value)
}
}
}
}
}