开发者

Cocoa: how to implement a custom NSView with an editable text area?

What's the minimum implementation needed to make a custom NSView with an editable text a开发者_开发技巧rea? I assume NSTextFieldCell can be used for this. I've succeeded in drawing the cell in the view (which is straightforward), but making it editable seems to require a more complicated coordination between the view and the cell. Is there sample code available somewhere?

Update. I should have made clear that my longer-term goal is to have many more editable text areas on the same view. AFAIU it is better to use cells in that case as they are more light-weight than full-blown views. My updated question is: What's the minimum implementation needed to make a custom NSView with an editable text area using an appropriate NSCell?


What's the minimum implementation needed to make a custom NSView with an editable text area?

  1. Make an NSView.
  2. Put an NSTextField in it.

Remember, NSViews (custom or otherwise) can contain other NSViews, and an NSTextField is a kind of NSView.

If you don't want code outside the custom view class to know about the text field, and it probably shouldn't, the custom view can create the text field and add it to itself as a private implementation detail. To do this, simply don't expose the text field in the custom view class's @interface (aside from the instance variable declaration, which is unavoidable).

The custom view should, of course, not draw wherever it put its text field. It could draw there, but the text field would cover it.

I assume NSTextFieldCell can be used for this.

Yes, if you don't mind reimplementing NSTextField. Adding an NSTextField as a subview of your view is much easier.


If you want to make a grid of text fields (with a dynamic number of them, perhaps), use an NSMatrix of NSTextFieldCells. You can, of course, add the NSMatrix as a subview of your custom view.


If you want to edit a text cell just call editWithFrame:inView:editor:delegate:event: on the cell object. This method requires the NSEvent that started the editing, so you can only call this from an event handler. There also is selectWithFrame:inView:editor:delegate:start:length: which sets up the field editor with an selection. You can use this if you need to start the editing from outside of an event handler.

After the user is done editing you need to call endEditing: on your cell.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜