繁体   English   中英

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

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

我的视图控制器中有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 ,但是无法以编程方式访问它。 有什么方法可以访问子类创建的对象?

要访问viewController路径,您必须将其定义为Public Variable并通过该类外部进行访问。

定义您的 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并进行与上述相同的访问。

谢谢。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM