Search code examples
iosobjective-cuiviewsubclassuibezierpath

How to access an object created by a subclass of UIView in a UIViewController


I have a subclass of UIView in my view controller that draws a UIBezierPath by finger touch:

#import "LinearInterpView.h"

@implementation LinearInterpView
{
    UIBezierPath *path;
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    if (self = [super initWithCoder:aDecoder])
    {
        [self setMultipleTouchEnabled:NO];
        [self setBackgroundColor:[UIColor colorWithWhite:0.9 alpha:1.0]];
        path = [UIBezierPath bezierPath];
        [path setLineWidth:2.0];

        // Add a clear button
        UIButton *clearButton = [[UIButton alloc] initWithFrame:CGRectMake(10.0, 10.0, 80.0, 40.0)];
        [clearButton setTitle:@"Clear" forState:UIControlStateNormal];
        [clearButton setBackgroundColor:[UIColor lightGrayColor]];
        [clearButton addTarget:self action:@selector(clearSandBox) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:clearButton];

    }
    return self;
}

- (void)drawRect:(CGRect)rect
{
    [[UIColor darkGrayColor] setStroke];
    [path stroke];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint p = [touch locationInView:self];
    [path moveToPoint:p];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint p = [touch locationInView:self];
    [path addLineToPoint:p];
    [self setNeedsDisplay];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self touchesMoved:touches withEvent:event];
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self touchesEnded:touches withEvent:event];
}

@end

Everything works just fine here, but I need to access the path generated by finger in my view controller and analyze it. When I debug the code, I can see variable path in the UIView which is present in my view controller, but I cannot access it programmatically. Is there any way to access an object created by a subclass?


Solution

  • To Access path into your viewController you have to define it as Public Variable and access it through outside that class.

    Define your : UIBezierPath *path; into @interface file and access it into ViewController

    @interface LinearInterpView
    {
        UIBezierPath *path;
    }
    

    like :

    LinearInterpView  *viewLinner = [LinearInterpView alloc]initwithframe:<yourFrame>];
    
    //By This line you can access path into your view controller.
    viewLinner.path 
    

    also you can create IBOutlet of that view and access same as above.

    Thanks.