Abhinav
Abhinav

Reputation: 752

HOw to show a custom subclass of UIView in ViewController

Xcode 5

I am trying to create a custom cropping rectangle to crop image. FOr that I understand I need to override drawRect() method in a class extending UIView. But then I don't know how to use that class in ViewController to show it.

Please correct if I am going in wrong direction. I am a little new to this.

MDCustomCropRect.h

#import <UIKit/UIKit.h>

@interface MDCustomCropRect : UIView

@end

MDCustomCropRect.m

- (void)drawRect:(CGRect)rect
{
    // Drawing code
    CGRect rectangle = CGRectMake(0, 100, 320, 100);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetRGBFillColor(context, 1.0, 1.0, 1.0, 0.0);   //this is the transparent color
    CGContextSetRGBStrokeColor(context, 0.0, 0.0, 0.0, 0.5);
    CGContextFillRect(context, rectangle);
    CGContextStrokeRect(context, rectangle);    //this will draw the border
}

Upvotes: 0

Views: 233

Answers (2)

Vinzzz
Vinzzz

Reputation: 11724

Just add your view as a subview of your UIViewController's view.

In your viewController code, typically in viewDidLoad method :

  // create your view
  MDCustomCropRect *myView = [[MDCustomCropRect alloc] init];
  [self.view addSubView:myView]  
  // you can manually set your view frame - in this case use initWithFrame: instead of init 
  // OR use layout constraints : define and add constraints AFTER your inserted your view as a subview

EDIT:

In your case, as you're only drawing a rectangle - which is what UIView is - you could instead to the following :

   UIView *myRectangleView = [[UIView alloc] initWithFrame:CGRectMake(0, 100, 320, 100)];
   myRectangleView.backgroundColor = [UIColor clearColor];
   myRectangleView.layer.borderWidth = 1;
   myRectangleView.layer.borderColor = [UIColor colorWithWhite:0 alpha:0.5].CGColor;
   [self.view addSubView:myRectangleView];

There is no need for a specific drawRect in your case

Upvotes: 1

Vineesh TP
Vineesh TP

Reputation: 7943

In your viewController

MDCustomCropRect *myView = [[MDCustomCropRect alloc] init];
myView.frame = CGRectMake(10,10,200,100);
myView.backgroundColor = [UIColor greenColor];
[self.view addSubView:myView] 

Upvotes: 1

Related Questions