Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

macos - Any example about custom NSComboBox?

I am asked to implement an combo box like this:

enter image description here

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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,

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?

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...