我有一个名为TargetView的子类化UIView,其中包含多个CGPath。当用户单击任何CGPaths(在UIView的触摸中开始时),我想对父视图控制器进行更改。这是来自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
}
}
我该怎么做?谢谢!
我建议您将父视图控制器设置为子视图控制器的委托。 然后,当在子视图控制器中检测到触摸时,可以调用委托进行响应。 这样,子视图控制器将仅具有对父视图控制器的弱引用。
if (CGPathContainsPoint(region, NULL, tap, NO)) {
[self.delegate userTappedPoint:tap];
}
父视图控制器的引用传递给分配时的UIView
,并将其存储在UIView
的属性中 然后,您有一个对父级的引用,您可以使用它来调用该父级上的方法/设置属性。
使用协议并将父视图控制器设置为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设置为此新协议的委托,并在其中实现方法ThatNeedToBeTriggered。