views:

70

answers:

2

I have an UIImageView and taking the raw touch input. I need to check if a touch is within a certain set of squares. At the moment...

I have this if statement....

if(46 < touchedAt.x && touchedAt.x < 124 && 18 < touchedAt.y && touchedAt.y < 75)

but I have tried to simplify it to this one...

if(46 < touchedAt.x < 124 && 18 < touchedAt.y < 75)

It didn't work. Is it possible to simplify like this or am I stuck with the slightly lengthier version at the top? Is there a reason why the types of comparisons in the bottom if don't work?

+5  A: 

I think a better solution would be to use CGRectContainsPoint:

CGRect rect = CGRectMake(46, 18, 124 - 46, 75 - 18);
if (CGRectContainsPoint(rect, touchedAt))
   // do whatever
Todd Yandell
This is a good alternative. As noted, your "shorter" syntax in the question is incorrect.
calmh
I guess this is where coming from a PHP background doesn't help sometimes. I like this alternative very much, it's a much nicer solution than what I am currently doing. However, I also like that Steve told me *why* my shorter version doesn't work.
JonB
As a general rule in Apple's APIs, any datatype defined by a framework usually has comparison functions written for it. This is especially true if the comparisons are very common such as this one. Moral: Look for the functions before writing code to duplicate them.
TechZen
+2  A: 

Some languages support the "simple" version (Python, for example) but the C family doesn't.

In C family languages, the comparison operators are binary operators that return a boolean. One operator, two parameters, one result. Try to add another comparison and you end up comparing your boolean result against the next value. That's why you need all the && operators.

I don't know Objective-C, but I assume it does what C does.

To simplify, just write a simple function (perhaps inline) called "bounds_check" or "range_check" or similar that takes three parameters. Or better still, use one that's already written.

Steve314
Objective-C is a strict superset of C. It does everything C does, exactly how C does it.
chpwn
@chpwn - very interesting. I keep meaning to take a look, but you know how it is - so many languages etc. Still, I'm interested in LLVM, so I'll certainly get around to playing with clang at some time, and that has objective C support IIRC.
Steve314