Tutorial :How do I draw text into a subview?



Question:

I want to draw text into UIView's subview using drawInRect:withFont:lineBreakMode call but that operates on the current context only.

Is it possible to draw text into a subview from current view?

The subview is a generic UIView instance and I don't really want to create a new UIView-derived class just for this purpose if I can avoid it.


Solution:1

One option would be to add a CALayer to the view's layer instead of adding a UIView to the view. The CALayer has a delegate property which you can assign any object to. The CALayer calls:

- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx  

on the delegate, which you can take to do something like:

- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx {      if (layer == myLayer) {          UIGraphicsPushContext(ctx);          [string drawInRect:rect withFont:font lineBreakMode:mode];          UIGraphicsPopContext();      }  }  


Solution:2

No, if you're going to do something with a context, you have to be in that view's -drawRect:. You can always make your subview a UIView subclass that overrides -drawRect: to display the text you want... but at that point, you're kind of reinventing UILabel.


Solution:3

No, you can't do what you describe. Subclassing UIView is exactly the method you're supposed to use for thisâ€" there's nothing wrong with creating a UIView subclass which only has a simple -drawRect: method.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »