iOS:根据它们相对于 sibling 的位置对一组 UIButton 进行排序?

标签 ios objective-c arrays sorting subview

我有一个 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/

相关文章:

C++读取文件,数组变量矩阵

php - 不必要的数组包装器

javascript - 如何从嵌套 JSON 有效负载 (JavaScript) 中删除特定元素?

javascript - 如何打开可编辑的对话框来发布推文

objective-c - 为什么边框粗细会随着按钮的颜色而变化(蓝色边框为 2px)?

iphone - 魔录iCloud更新核心数据

ios - 以编程方式将 subview 添加到 UIView - ios

iOS 在 View Controller 消失后隐藏 Touch ID

ios - 嗨,有没有办法让 AVSpeech 合成器在使用耳机播放音频的同时使用任一 channel 播放音频?

ios - Swift/NSURLSession JSON 下载/在展开可选值时意外发现 nil