2

Is there any way to add a second parameter in a custom UIView class in the drawRect method?

I am currently using a UIView to draw a text string but the text itself is set in the drawRect method. Is there any way to pass in the text variable in something like

- (void) drawRect:(CGRect)rect(NSString *)text

and if not are there any alternative work arounds?

Thanks

Steven Ritchie
  • 228
  • 1
  • 2
  • 12

1 Answers1

2

You would generally have a custom @property for your UIView subclass:

@property (nonatomic, copy) NSString *text;

You might even have a custom setter that calls setNeedsDisplay, such that when you set the text property, the view's drawRect will get called, e.g.:

- (void)setText:(NSString *)text
{
    _text = [text copy];
    [self setNeedsDisplay];
}

Your drawRect could then reference self.text when it needs to reference that NSString.

Rob
  • 415,655
  • 72
  • 787
  • 1,044
  • Hi, Rob, in the setter you use _text but in drawRect you refer it as self.text, may I know why you do so? Thanks. – Unheilig Nov 06 '13 at 19:30
  • 1
    Perfect, thanks! I should have thought of this. I used the property and then set the text in my view controller before adding the custom view as a subview. – Steven Ritchie Nov 06 '13 at 19:49
  • 2
    @Unheilig The critical observation is that you should not use `self.text` to set the property in the setter, because `self.text = ...` translates to `[self setText:...]`, and you'll get infinite recursion. You should never use accessor methods (setters and getters) in the accessor methods, themselves (or in the `init` and `dealloc` methods, either). In `drawRect`, you can use the synthesized ivar, `_text`, to retrieve the value if you want (it's a matter of a personal preference), but I always use the getter where I can, as it offers the greatest flexibility with negligible overhead. – Rob Nov 06 '13 at 20:07
  • @Unheilig The [Use Accessor Methods to Make Memory Management Easier](https://developer.apple.com/library/mac/documentation/cocoa/conceptual/memorymgmt/Articles/mmPractical.html#//apple_ref/doc/uid/TP40004447-SW4) section of the _Advanced Memory Management Programming Guide_ outlines where one should and should not use the accessor methods. – Rob Nov 06 '13 at 20:10
  • 1
    @Rob Very nice explanation. Yes, that rang a bell - recursion. Thanks. – Unheilig Nov 06 '13 at 20:20