Bind enabled of NSButton to selection in NSTextView
-
27-09-2019 - |
Question
I have a button that does something to the selected text in NSTextView. If nothing is selected then nothing happens when the button is pressed... so can the enabled property of a button be bound to whether or not some text is selected?
Solution
You don't want to bind a view to another view, anyway. The Right Way is to bind views to controllers, and Bindings gets cranky when you don't do things the Right Way.
Bind the button's enabled
property to a property of the controller. Have the controller be the delegate of the text view, and when the text view's selections change, update the controller's property accordingly.
If no text (was|is) selected, then the (old|new) selection ranges array will contain exactly one NSValue object, whose rangeValue
will be a zero-length range. This range is that of the insertion point; its length will be zero (nothing selected), but its location may not be (it will be wherever the insertion point is).