Best way to add text labels to my view?

Discussion in 'Mac Programming' started by jeanlain, Dec 15, 2012.

  1. jeanlain macrumors 65816

    Mar 14, 2009
    Hello, I have an NSView that draws a chromatogram (a curve) and also draws text labels above the tip of peaks (the text represents the x location of the peak). I'm currently using NSTextField instances as subviews of the chromatogram view for these labels, and it seems to work.
    However, the Apple documentation suggests NSCell should be more adapted to draw text in a view ("lighter" than NSControl, they say). But I can't get how it's supposed to work. I tried to create cells and send -drawWithFrame:inView: to them, but they seem to draw in the window coordinate (even though the inView: argument is the chromatogram view) so they show outside the view. I don't even know exactly when I should call this method either (assuming it's the right method). Should I call it within the view -drawRect: method? Should I subclass NSCell and override some methods? NSTextField instances draw themselves, so I don't have to worry about it, I just have to set their frame so they draw at the right spot. But for NSCell... I don't know how.
    The labels should ultimately react to mouse event and send actions... which is why I'm not simply drawing strings with -drawAtPoint:

    So, should I use NSCell (if so, how?) or is NSTextField the best solution?

  2. Sydde macrumors 68020


    Aug 17, 2009
    The inView: argument does not seem to mean anything, per the documentation. You would have to bracket the method with a focus lock on the chromatograph view, or just make sure it has locked focus.

    But cells do not have built-in frames, so by themselves, they do not have a whole lot to offer, other than that they might be a little more efficient than drawing attributed strings directly if you have to do it a lot. If you use cells, I think you still have to resolve mouse hits in your view's event methods, so cells a not a huge gain.

    If the drawing is a big load and the label text is static (unlikely to change very often), one thing you could do is put the label into a NSImage and draw that where you need it, but then you still have to handle events in your view. The easiest road is to just use a borderless button or text field, which would chew a bit more ram but mean much less work for you.
  3. jeanlain thread starter macrumors 65816

    Mar 14, 2009
    Thanks for the reply.
    Since the the user can resize and scroll the chromatogram, I indeed need to reposition the labels very often (there are about 20 labels per view). But I found that I just needed to call "-drawWithFrame:inView" within the -drawRect: method of the view and it worked fine. Calling outside of this method simply draws cells in the window coordinates, for some reason.
    However, I'm not sure it's a better option than text fields to receive user input and send actions. I'll see.

Share This Page