According to documents i read, they always show that I should define a subview in a class. Like this : @interface PolygonView : UIView. I have to inherit from UIView.

Could i define a variable with UIView type in a class which inherit from NSObject? After that, i make a connection from that variable to UIView which is defined in Interface Builder. The problem is that i can not override - (void)drawRect:(CGRect)rect

+2  A: 

Generally you'll do something like this

@interface MyView : UIView {
// Declare IBOutlets here if you wish or other instance variables you may need

@implementation MyView

- (void)drawRect:(CGRect)rect {
// Drawing stuff

And then in Interface Builder, create a view (usually by making a View XIB or by dragging out a Custom UIView object onto (well, into) another UIView in the XIB thus making it a subview) and then in the Inspector pane, set its Class to be MyView. Then you can connect any IBOutlets you've defined in the MyView interface declaration.


Yes, you can define a variable in a plain NSObject subclass that points to a UIView. But if you do, of course you can't override drawRect: — that object just has a reference to a UIView, it isn't a view itself. It's much like you can have a variable that's an int, but that doesn't mean the object containing that variable is an int.

If you want to override a view's drawing, you need to make a view. You can still have a separate class that interacts with your UIView subclass from outside.

I've used vanilla `UIView`s many times before. You can set their `backgroundColor` and you've essentially got a coloured rectangle. Not only that, they can be used as generic containers for subviews. It's probably not what the poster is looking for, but there are legit reasons for doing it that way.
@jbrennan: What are you talking about? I never said you couldn't do that.
I know, just wanted to mention sometimes `UIView` is useful even without subclassing. It works in tandem with your answer.