Reputation: 4755
I have a NSMutableArray
, called self.tappableButtons
, of UIButtons
which all share the same parent view. At times they overlap, and I would love to sort my array based on their order in relation to each other (starting with the topmost button to the bottommost one in the hierarchy). What's the easiest way to achieve this?
I'm basically using fast enumeration to check if the current touch in my custom pan gesture recognizer falls within a button's bounds. The problem is that if two buttons overlap it returns the one that came first in my array when enumerating, rather than the topmost button within an overlap.
//Search through all our possible buttons
for (UIButton *button in self.tappableButtons) {
//Check if our tap falls within a button's view
if (CGRectContainsPoint(button.bounds, tapLocation)) {
return button;
}
}
Upvotes: 1
Views: 187
Reputation: 17705
The easiest way (without knowing more of your code) is probably to use the subviews
order to determine the topmost button on your touch.
UIView* buttonParentView = ....
NSEnumerator* topToBottom = [buttonParentView.subviews reverseObjectEnumerator];
for (id theView in topToBottom) {
if (![self.tappableButtons containsObject: theView]) {
continue;
}
UIButton* button = (UIButton*)theView;
//Check if our tap falls within a button's view
if (CGRectContainsPoint(button.bounds, tapLocation)) {
return button;
}
}
If this function is executed a lot and your self.tappableButtons
remains relatively stable, or your parentview has a -lot- of subviews that are not in self.tappableButtons
it's probably better to simply use your function but sort the tappableButtons first based on where they appear in their parents subviews.
Upvotes: 1