2016-08-04 58 views
0

我已經子類化了一個NSSlider,它的行爲與選擇鍵是否按下不同。爲了做到這一點,我覆蓋了mouseDown函數。它似乎做的工作。 事情是,我已經注意到,當ViewController中的連接@IBAction僅在未按下選項鍵時(即,當mouseDown方法傳遞給super時)觸發。我爲了讓@IBAction執行而丟失了什麼?子類NSControl,IBAction不在Swift中調用

非常感謝 除了問題,對代碼改進建議,歡迎... :-)

喬希

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

回答

1

如果你不打電話super.mouseDown,你需要發送的動作自己:

sendAction(action, to: target) 

sendAction(_:to:)actiontarget是現有成員。

+0

它的工作原理! self.sendAction(self.action,to:nil)謝謝! – Joshua