I prepared an example application, so consider the following:
https://github.com/melifaro-/DraggableNSTextFieldSample
The idea is to introduce a SelectableTextField that inherits from NSTextField . SelectableTextField provides the ability to subscribe to an invited listener for a text field selection event. It has a didSelectCallback block variable where you need to set the processing code. Something like that:
textField.didSelectCallback = { (textField) in //this peace of code will be performed once mouse down event //was detected on the text field self.currentTextField = textField }
Using the specified callback mechanism, after selecting a text field, we can save it in the currentTextField variable. Thus, when the mouseDragged function is ViewController , we know currentTextField , and we can handle it accordingly. In the case of the sample application, we need to adjust the start of currentTextField to shift the shift event. Hope it got better now.
PS NSTextField opens for inheritance, so you can freely use our SelectableTextField wherever you use NSTextField, including Interface Builder.
EDIT
I checked your sample. Unfortunately, I cannot commit / create a transfer request to your repository, so find my suggestion here:
override func viewDidLoad() { super.viewDidLoad() didButtonSelectCallback = { (button) in if let currentButton = self.currentButton { currentButton.highlighted = !currentButton.highlighted if currentButton == button { self.currentButton = nil } else { self.currentButton = button } } else { self.currentButton = button } button.highlighted = !button.highlighted } addButtonAtRandomePlace() addButtonAtRandomePlace() didButtonSelectCallback(button: addButtonAtRandomePlace()) } override func mouseDragged(theEvent: NSEvent) { guard let button = currentButton else { return } NSCursor.closedHandCursor().set() button.frame.origin.x += theEvent.deltaX button.frame.origin.y -= theEvent.deltaY } private func addButtonAtRandomePlace() -> SelectableButton { let viewWidth = self.view.bounds.size.width let viewHeight = self.view.bounds.size.height let x = CGFloat(rand() % Int32((viewWidth - ButtonWidth))) let y = CGFloat(rand() % Int32((viewHeight - ButtonHeight))) let button = SelectableButton(frame: CGRectMake(x, y, ButtonWidth, ButtonHeight)) button.setButtonType(NSButtonType.ToggleButton) button.alignment = NSCenterTextAlignment button.bezelStyle = NSBezelStyle.RoundedBezelStyle button.didSelectCallback = didButtonSelectCallback self.view.addSubview(button) return button }
source share