【问题标题】:UIViewController needs to respond to events from subclassed UIViewUIViewController 需要响应来自子类 UIView 的事件
【发布时间】:2014-03-05 14:47:29
【问题描述】:

我有一个名为 TargetView 的子类 UIView,其中包含多个 CGPath。当用户单击任何 CGPaths(在 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
    }
}

我该怎么做?谢谢!

【问题讨论】:

    标签: ios iphone uiview uiviewcontroller


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:

        使用 protocol 并将父视图控制器设置为 UIView 的 delegate

        在您的 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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-09-21
          • 2013-07-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-01-14
          相关资源
          最近更新 更多