【问题标题】:Event listener for the position of a UIImageViewUIImageView 位置的事件监听器
【发布时间】:2011-07-03 16:30:13
【问题描述】:

如何根据 UIImage 视图的 y 坐标调用方法? 更具体地说,我有一个可拖动的 UIImageView。当它的y坐标大于某个值时,我希望屏幕的颜色发生变化。

拖拽代码:

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

UITouch *touch = [[event allTouches] anyObject];

 if([touch view] == toggle)

 {



    CGPoint location = [touch locationInView:self.view];
    CGPoint newLocation = CGPointMake(toggle.center.x, location.y);

    toggle.center = newLocation;
    NSLog(@"%f \n",toggle.center.y);

}  

}

【问题讨论】:

  • 您必须更具体:坐标何时可见?被感动了?有某种颜色吗?
  • 顺便说一句:我删除标签是有原因的——它们毫无意义。
  • 怎么拖是什么意思。我猜是通过触摸和拖动。
  • 你有一些代码吗?
  • 我的问题与拖动无关。我只想知道如何监听 UIImageView 的 y 坐标的变化并根据变化执行方法。

标签: iphone objective-c cocoa-touch uiimageview


【解决方案1】:

我可以想到两种方法。首先是Key-Value Observing,通过以下方式:

[self.toggle addObserver: inspector
              forKeyPath: @"frame"
                 options: NSKeyValueObservingOptionNew
                 context: NULL];

不过,我不确定 frame 属性是否符合键值编码。

或者,这是我的建议,您可以:

(1) 创建一个 [Prefix]ToggleViewLocationDelegate 协议,并将 locationDelegate 属性添加到您的视图/视图控制器,如下所示:

// YourViewOrViewControllerClass.h
// ...


@class YourViewOrViewControllerClass

@protocol [Prefix]ToggleViewLocationDelegate

- (void) toggleViewDidChangeFrame: (UIView*) toggleView;

@end

@class YourViewOrViewControllerClass

@property (nonatomic, assign) id<[Prefix]ToggleViewLocationDelegate> locationDelegate;
...

@end

(2) 使对坐标变化感兴趣的类符合协议,并且 (3) 在touchesMoved:withEvent:方法中,通知locationDelegate,如下:

- (void) touchesMoved: (NSSet*)   touches
            withEvent: (UIEvent*) event
{
  UITouch* touch = [touches anyObject];
  if (touch.view == toggle)
  {
    /* Fetch the new touch location */
    CGPoint location = [touch locationInView: self.view];

    /* Set the toggle's location */
    CGPoint newLocation = CGPointMake(toggle.center.x, location.y);
    toggle.center = newLocation;

    /* Inform the delegate when applicable */
    if (self.locationDelegate != nil)
    {
      [self.locationDelegate toggleViewDidChangeFrame: toggle];
    }
  }
}

【讨论】:

    猜你喜欢
    • 2013-01-24
    • 2013-09-15
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 2014-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多