gpt4 book ai didi

swift - 子类化 NSControl,IBAction 在 Swift 中不被调用

转载 作者:行者123 更新时间:2023-11-28 12:43:28 25 4
gpt4 key购买 nike

我已经将一个 NSSlider 子类化,无论是否按下 option 键,它的行为都不同。为此,我覆盖了 mouseDown 函数。它似乎完成了这项工作。问题是,我注意到我的 ViewController 中连接的 @IBAction 仅在未按下选项键时触发(即,当 mouseDown 方法传递给 super 时)。为了允许 @IBAction 执行,我缺少什么?

非常感谢除了这个问题,欢迎对代码提出改进建议... :-)

乔希

class ViewController: NSViewController {

@IBOutlet weak var theSlider: MySlider!
@IBAction func moveSlider(sender: NSSlider) {
print(sender.floatValue) //works only with optionKey unpressed
}
}

class MySlider: NSSlider { //Implemented in another source file

@IBInspectable var multiplier: Float = 0.5
private var modifierKeys = NSEventModifierFlags.AlternateKeyMask
private var optionKeyPressed = false
private var previousSliderPosition: Float = 0.0

//MARK: Init with NSCoder
required init?(coder: NSCoder) {
super.init(coder: coder)
Swift.print("init Coder called")

self.continuous = true
NSEvent.addLocalMonitorForEventsMatchingMask(.FlagsChangedMask) { (theEvent) -> NSEvent? in
self.flagsChanged(theEvent)
return theEvent
}
}

//MARK: Mouse tracking
override func mouseDown(theEvent: NSEvent) {

if optionKeyPressed {

var keepOn = true
previousSliderPosition = self.floatValue * Float(self.bounds.width) / Float(self.maxValue)

while keepOn {
if let nextEvent = self.window?.nextEventMatchingMask(Int(NSEventMask.LeftMouseUpMask.rawValue) | Int(NSEventMask.LeftMouseDraggedMask.rawValue))
{
switch nextEvent.type
{
case .LeftMouseDragged:
let mouseInnerLocationX = Float(self.convertPoint(nextEvent.locationInWindow, fromView: self.superview).x)
let mouseDelta = mouseInnerLocationX - previousSliderPosition
let newSliderPosition = previousSliderPosition + (mouseDelta) * multiplier

self.floatValue = newSliderPosition * Float(self.maxValue) / Float(self.bounds.width)
break

case .LeftMouseUp:
keepOn = false
break

default:
break
}
}
}
} else {
super.mouseDown(theEvent)
}
}

//MARK: Option key handling
override func flagsChanged(theEvent: NSEvent) {
if (theEvent.modifierFlags.rawValue & NSEventModifierFlags.DeviceIndependentModifierFlagsMask.rawValue) == NSEventModifierFlags.AlternateKeyMask.rawValue {
optionKeyPressed = true
} else {
optionKeyPressed = false
}
}
}

最佳答案

如果你不调用 super.mouseDown ,你需要自己发送 Action :

sendAction(action, to: target)

sendAction(_:to:) , actiontargetNSControl 的现有成员.

关于swift - 子类化 NSControl,IBAction 在 Swift 中不被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38778924/

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