Reputation: 33644
So I have a UIWebView which I have added a touch gesture in it, and I would like to find the x,y origin coordinates of an image tapped in the web view or if possible the center of the image in x y coordinates in the web view. The code I have is:
- (CGPoint) topLeftPointsForImage:(UIGestureRecognizer *)sender
{
CGPoint pt = [sender locationInView:self];
NSString * offsetTop = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).offsetTop", pt.x, pt.y
];
NSString * offsetLeft = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).offsetLeft", pt.x, pt.y
];
NSString * scrollTop = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).parentNode.scrollTop", pt.x, pt.y
];
NSString * scrollLeft = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).parentNode.scrollLeft", pt.x, pt.y
];
float x = [[self stringByEvaluatingJavaScriptFromString:offsetTop] floatValue] - [[self stringByEvaluatingJavaScriptFromString:scrollTop] floatValue];
float y = [[self stringByEvaluatingJavaScriptFromString:offsetLeft] floatValue] - [[self stringByEvaluatingJavaScriptFromString:scrollLeft] floatValue];
NSLog(@"Coor height is %f with coor width is %f", x, y);
CGPoint point = CGPointMake(x, y);
return point;
}
However, this doesn't seem to give me a correct value. I am not a javascript master, so looking for some advice for this.
Upvotes: 0
Views: 1289
Reputation: 11
If you use jQuery in your html page, then you may try to use :
NSString * offsetTop = [NSString stringWithFormat:@"$(document).elementFromPoint(%f, %f).offsetTop;", pt.x, pt.y
];
also note the semi-colon at the end of the statement. All Javascript statements must be valid and properly terminated, just like inside a html page.
If you are injecting a library, you have to properly put into a function class with namespaces, as follows:
"(function () {return "your data";}) ();"
Upvotes: 1