I am asked to implement an combo box like this:
It is clear that this is quite different from NSComboBox:
<1> The button of beside the text field should be customized
<2> This is much more important: there is an additional "cross" (which is a button indicating "delete" action) in each of the combo item.
How can I achieve this effect? I searched for the internet but fount no answer. Could any one tell me what I should make this or tell me any example of subclassing or customizing NSComboBox class?
NSComboBox is a view, but for reasons I won't go into here it's interface is drawn by an accompanying cell class: NSComboBoxCell. For custom drawing you normally have to subclass the cell type (in this case NSComboBoxCell), implement all the drawing you want in your custom cell subclass and then make the view use your cell with the -setCellClass:
or -setCell:
method.
However, in this case NSComboBox inherits from NSTextField, and NSComboBoxCell inherits from NSTextFieldCell, so both already implement -setBackgroundColor: and -setTextColor:; so it should be fairly easy to draw the white background and blue text.
I'm not sure how NSComboBox draws the 'drop down menu', I can't see any way of customising that, but I'm sure it's possible. You will probably have to play around inside the NSCell's drawing methods to see,
- -drawInteriorWithFrame:inView:,
- -drawWithFrame:inView:,
- -drawWithExpansionFrame:inView:
The final problem you will have is putting the cross inside the text field. You will have to implement the drawing of the cross using the NSCell's drawing methods above. However, to intercept the mouse clicks you would need to do that with an NSView (because NSCell's don't deal with interactions). This means you also need to subclass NSComboBox and keep track of when the mouse enters the part of the view where the cross is drawn.
This is all rather complicated so maybe there is another way. Are you aware of NSPopover?
It would be much easier to implement something similar with NSPopover. The popover holds a view so you don't have to mess around with an NSCell methods. The popover could contain the list of names and an NSButton (which is the cross).