事件监听器,用于UIImageView的位置

时间:2011-07-03 16:30:14

标签: iphone objective-c cocoa-touch uiimageview

如何根据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);

}  

}

1 个答案:

答案 0 :(得分:0)

我可以想到两种方法。首先是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];
    }
  }
}