tags:

views:

914

answers:

2

I have created a view and would like to draw or add text to it later based on the state of app when user touches it.

Can I do this with drawRect given that I have multiple possible draw/text items for it? If so, how do you invoke it? If not, where should I look to accomplish this?

Thanks in advance,

Steve

A: 

The best way to draw simple objects, like text, images from files, or, say, solid-color rectangles, is simply to add those elements as subviews of your view. Generally, it's much easier to never worry about the drawRect: method unless you need to do something you can't do by adding subviews. For example, if you want to create a pie chart based on some dynamic data, it might make sense to write your own drawing routines. Otherwise, when you only work with views and subviews, drawRect: is always called for you automatically whenever it is appropriate, including if you change any properties of these objects that would call for a visual difference, such as changing the font color, or the pixel coordinates of a subview.

Here's a quick example of how you might add two subviews to a view, such as in the loadView method of a view controller:

CGRect helloFrame = CGRectMake(10, 10, 100, 50);
UILabel* helloLabel = [[UILabel alloc] initWithFrame:helloFrame];
helloLabel.text = @"hello,";
helloLabel.textColor = [UIColor redColor];
[self.view addSubview:helloLabel];

CGRect worldFrame = CGRectMake(60, 60, 100, 50);
UILabel* worldLabel = [[UILabel alloc] initWithFrame:worldFrame];
worldLabel.text = @"world!";
worldLabel.textColor = [UIColor orangeColor];
[self.view addSubview:worldLabel];
Tyler
In defense of my answer (because it has negative votes right now): The question makes it sound as if SE Powell might be thinking of drawRect: as the only way to build a custom view, which is a bad misconception. My answer is trying to look at the bigger picture and give the answer that will be most useful in the long run as a coding technique.
Tyler
+1  A: 

You can invalidate a UIView by calling

[myView setNeedsDisplay];

Which will have the OS call drawRect for myView at an appropriate time.

fbrereto