如何在UIViewController中访问由UIView的子类创建的对象

时间:2017-03-18 02:02:38

标签: ios objective-c uiview subclass uibezierpath

我的视图控制器中有一个UIView的子类,通过手指触摸绘制UIBezierPath:

#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

这里的一切都运行得很好,但我需要在我的视图控制器中访问手指生成的路径并对其进行分析。当我调试代码时,我可以在UIView中看到变量path,它存在于我的视图控制器中,但我无法以编程方式访问它。有没有办法访问子类创建的对象?

1 个答案:

答案 0 :(得分:0)

要访问viewController的路径,您必须将其定义为公共变量,并通过该类外部访问它。

将您的 UIBezierPath *path;定义到@interface文件并将其访问到ViewController

@interface LinearInterpView
{
    UIBezierPath *path;
}

喜欢:

LinearInterpView  *viewLinner = [LinearInterpView alloc]initwithframe:<yourFrame>];

//By This line you can access path into your view controller.
viewLinner.path 

您也可以创建该视图的IBOutlet并访问上述内容。

感谢。