UIViewController需要响应来自子类UIView的事件

时间:2014-03-05 14:47:29

标签: ios iphone uiview uiviewcontroller

我有一个名为TargetView的子类UIView,它包含几个CGPath。当用户点击任何一个CGPath(在UIView的touchesBegan中)时,我想对父视图控制器进行更改。这是来自TargetView(UIView)的代码

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

    CGPoint tap = [[touches anyObject] locationInView:self];

    if(CGPathContainsPoint(region, NULL, tap, NO)){
        // ...do something to the parent view controller
    }
}

我怎么能这样做?谢谢!

3 个答案:

答案 0 :(得分:1)

我建议您将父视图控制器设置为子视图控制器的委托。然后,当在子视图控制器中检测到触摸时,您可以调用委托进行响应。这样,您的子视图控制器将只具有对父级的弱引用。

if (CGPathContainsPoint(region, NULL, tap, NO)) {
    [self.delegate userTappedPoint:tap];
}

答案 1 :(得分:0)

您需要将对父viewController的引用传递给UIView分配,并将其存储在UIView的属性中然后您有对父级的引用,您可以使用它来在该父级上调用方法/设置属性。

答案 2 :(得分:0)

使用协议并将父视图控制器设置为UIView的委托

在你的UIView子类.h文件中:

@protocol YourClassProtocolName <NSObject>

@optional
- (void)methodThatNeedsToBeTriggered;

@end

@interface YourClass : UIView

...

@property(weak) id<YourClassProtocolName> delegate;

@end

在.m文件中:

@interface YourClass () <YourClassProtocolName>
@end

@implementation YourClass
...

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

    CGPoint tap = [[touches anyObject] locationInView:self];

    if(CGPathContainsPoint(region, NULL, tap, NO)){
        if (_delegate && [_delegate respondsToSelector:@selector(methodThatNeedsToBeTriggered)]) {
            [_delegate methodThatNeedsToBeTriggered];
        }
    }
}
@end

现在将UIViewController设置为此新协议的委托,并在其中实现 methodThatNeedsToBeTriggered