gpt4 book ai didi

Swift-4 MacOS 检测鼠标滚轮在 NSTextField 上滚动?

转载 作者:搜寻专家 更新时间:2023-11-01 06:14:32 25 4
gpt4 key购买 nike

我在使用 Swift-4 的 MacOS 应用程序上有一个 NSTextField

它的目的是让用户输入一个数字。有没有办法根据鼠标滚轮的向上滚动或向下滚动来更改数字?

最佳答案

您可以覆盖 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)
}
}
}

如果您只想更改具有焦点的字段,您可以使用 View 窗口字段编辑器:

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)
}
}

如果您想将滚动限制为仅特定字段,您需要将 View Controller 设置为它的委托(delegate)并将其委托(delegate)与文本字段对象进行比较:

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)
NSSound(named: "Tink")?.stop
if view.window?.firstResponder?.textView?.delegate === textField1,
let text = view.window?.fieldEditor(false, for: nil),
var value = Int(text.string) {
if event.deltaY < 0 { value += 1 }
if event.deltaY > 0 { value -= 1 }
NSSound(named: "Tink")?.play()
text.string = String(value)
print(value)
}
}
}

extension NSResponder {
var textView: NSTextView? { return self as? NSTextView }
}

关于Swift-4 MacOS 检测鼠标滚轮在 NSTextField 上滚动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47909725/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com