NSButton subclass that responds to right clicks

后端 未结 3 1217
余生分开走
余生分开走 2021-01-19 01:10

I have an NSButton subclass that I would like to make work with right mouse button clicks. Just overloading -rightMouseDown: won\'t cut it, as I would like the

3条回答
  •  悲哀的现实
    2021-01-19 01:29

    Not much to add to the answers above, but for those working in Swift, you may have trouble finding the constants for the event mask, buried deep in the documentation, and still more trouble finding a way to combine (OR) them in a way that the compiler accepts, so this may save you some time. Is there a neater way? This goes in your subclass -

    var rightAction: Selector = nil 
      // add a new property, by analogy with action property
    
    override func rightMouseDown(var theEvent: NSEvent!) {
      var newEvent: NSEvent!
    
      let maskUp = NSEventMask.RightMouseUpMask.rawValue
      let maskDragged = NSEventMask.RightMouseDraggedMask.rawValue
      let mask = Int( maskUp | maskDragged ) // cast from UInt
    
      do {
        newEvent = window!.nextEventMatchingMask(mask)
      }
      while newEvent.type == .RightMouseDragged
    

    My loop has become a do..while, as it always has to execute at least once, and I never liked writing while true, and I don't need to do anything with the dragging events.

    I had endless trouble getting meaningful results from convertRect(), perhaps because my controls were embedded in a table view. Thanks to Gustav Larsson above for my ending up with this for the last part -

    let whereUp = newEvent.locationInWindow
    let p = convertPoint(whereUp, fromView: nil)
    let mouseInBounds = NSMouseInRect(p, bounds, flipped) // bounds, not frame
    if mouseInBounds {
      sendAction(rightAction, to: target)
      // assuming rightAction and target have been allocated
      }
    }
    

提交回复
热议问题