Search code examples
iosipadcore-graphicsquartz-2d

Overriding drawRect method in a UIView subclass & call it into another UIViewcontroller


I am a novice ios programmer and this is my first project.I am going to develop this project specifically for ipad. In this project i need to draw several circles & display data on it by parsing xml element.I have done the the circle drawing part by subclassing UIView class and overriding drawRect method. I load the UIView subclass in a UIViewcontroller via loadview method .Now what i need to do is

  • Touch a circle and switch to another UIViewcontroller.

I am not sure how to switch to another UIViewcontroller because all of drawing and touch detecting code is in my UIView subclass.

A help will be appreciated


Solution

  • You need to use a delegate method to tell the parent view controller that there was a touch, so it can present another view controller.

    At the top of your UIView subclass header, add this:

    @protocol MyCustomViewDelegate <NSObject>
    
    - (void)customViewCircleTapped;
    
    @end
    

    Then, in your declaration of the view (the existing declaration you have of your custom view subclass):

    @interface MyCustomView : UIView
    
    ...
    
    @property (weak) id<MyCustomViewDelegate> delegate;
    

    After that, in your view controller, you need to set view.delegate = self, so the view can reference the view controller.

    Then, in your view controller header, change your declaration to look like this:

    @interface MyViewController : UIViewController <MyCustomViewDelegate>
    

    then implement customViewCircleTapped in the view controller implementation:

    - (void)customViewCircleTapped {
        ... // Open a view controller or something
    }
    

    Once you have done that, in the touch detection code in your view, you can add:

    [self.delegate customViewCircleTapped];
    

    What this does is gives your custom view the ability to tell its parent view controller that something has happened, by calling this method (you can change it and add arguments if you need to pass data), and then the view controller can open another view controller or perform some action based on this.

    View detects touches → Process touches → call customViewCircleTapped delegate method on view controller → view controller opens another view controller