我有一个 NSMutableArray
,称为 self.tappableButtons
,属于 UIButtons
,它们都共享相同的父 View 。有时它们会重叠,我很乐意根据它们彼此相关的顺序对我的数组进行排序(从最顶层的按钮开始到层次结构中最底部的按钮)。实现这一目标的最简单方法是什么?
我基本上使用快速枚举来检查我的自定义平移手势识别器中的当前触摸是否落在按钮的范围内。问题是,如果两个按钮重叠,它会在枚举时返回我的数组中第一个出现的按钮,而不是重叠中最上面的按钮。
//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
保持相对稳定,或者你的parentview有-很多-不在self.tappableButtons
中的 subview 简单地使用您的函数可能更好,但首先根据它们在父 subview 中出现的位置对 tappableButtons 进行排序。
关于iOS:根据它们相对于 sibling 的位置对一组 UIButton 进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28874545/