Quote:
Originally Posted by tharindufit
Hi,
I want to implement a custom UIView with a UILabel and an ImageView, I think I need to implement two methods after extending UIView class, drawRect and initWithFrame:
But I am not clear on how to do this. I have tried adding UILabel and ImageView as subviews at my drawrect but It did not work. Can any one help me on this. I would like to have some example custom UIView class code, where I can study and understand.
Thanks.
Tharindu
|
If you want a view that includes a label and an image view, you can just create a UIView and add the label and the image view as subviews. Any objects you add as subviews will be drawn automatically.
You can add subviews to a UIView either in Interface Builder or in code. Both approaches work. It's a little easier in IB, but not that difficult in code either. You would add the subviews when the view is created, not in it's -drawRect. (The drawRect method gets called every time the view needs to redraw itself, so if you add subviews in your drawRect method you would end up adding subviews over and over and over, until you run out of memory and crash.)
It's actually unusual to subclass UIView such that you need to implement a custom drawRect method. Apple actually discourages it, since most of the view objects built into iOS are highly optimized for working with the graphics hardware, and drawing with code in -drawRect requires code that runs on the CPU.
Note that if you have a custom subclass of UIView, that subclass can both do drawing in a custom -drawRect method, AND contain subviews that draw themselves automatically. The subviews will be drawn on top of the superview.
As an example, I have a "boxed view" class I use sometimes that is a UIView that will draw a box around itself, either with square or rounded corners. I use this to create the grouping box look from Mac OS. I can create a bunch of labels, text views, buttons, etc, and put them inside one of my boxed views as subviews. The boxed view object draws a box around itself, and then other items take care of drawing themselves.