Event listener for the position of a UIImageView
How would I be able to call a method, according to the y coordinate of a UIImage view? To be more specific, I have a dragable UIImageView. When the y co-ordinate of it is greater than a certain开发者_如何转开发 value, I want the colour of the screen to change.
code for dragging:
- (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);
}
}
I could think of two ways of doing this. First is Key-Value Observing via the following:
[self.toggle addObserver: inspector
forKeyPath: @"frame"
options: NSKeyValueObservingOptionNew
context: NULL];
I'm not sure if the frame
property is Key-Value Coding compliant, though.
Or, and this is what I would recommend, you can:
(1) Create a [Prefix]ToggleViewLocationDelegate protocol, and add a locationDelegate property to your view/view controller, like so:
// YourViewOrViewControllerClass.h
// ...
@class YourViewOrViewControllerClass
@protocol [Prefix]ToggleViewLocationDelegate
- (void) toggleViewDidChangeFrame: (UIView*) toggleView;
@end
@class YourViewOrViewControllerClass
@property (nonatomic, assign) id<[Prefix]ToggleViewLocationDelegate> locationDelegate;
...
@end
(2) Make the class interested in the coordinate changes conform to the protocol, and
(3) In the touchesMoved:withEvent:
method, inform the locationDelegate
, like so:
- (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];
}
}
}
精彩评论