Any example about custom NSComboBox?

微笑、不失礼 提交于 2019-11-28 04:43:01

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/21361766/any-example-about-custom-nscombobox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!