iOS:根据UIButtons相对于其兄弟姐妹的位置对其数组进行排序



我有一个UIButtonsNSMutableArray,称为self.tappableButtons,它们都共享同一个父视图。有时它们会重叠,我很乐意根据它们相对于彼此的顺序对数组进行排序(从层次结构中最顶部的按钮到最底部的按钮)。实现这一点最简单的方法是什么?

我基本上是使用快速枚举来检查我的自定义平移手势识别器中的当前触摸是否在按钮的范围内。问题是,如果两个按钮重叠,它会返回枚举时数组中第一个出现的按钮,而不是重叠中最顶部的按钮。

//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;
        }    
}

最简单的方法(在不了解更多代码的情况下)可能是使用subviews顺序来确定触摸屏上最顶部的按钮。

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;
     }    
}

如果这个函数执行了很多次,并且您的self.tappableButtons保持相对稳定,或者您的父视图有很多不在self.tappableButtons中的子视图,那么最好简单地使用您的函数,但首先根据可点击按钮在父视图中的显示位置对其进行排序。

最新更新