根据iOS中的位置对UIView子视图进行x排序

时间:2018-07-12 07:15:59

标签: ios iphone swift uitabbar

我需要找到UITabBarButton位置,我已经实现了用于获取tabbutton和传递的索引的所有值的方法。但是在子视图中初始标签栏按钮的获取是未排序的方式。下面是我的代码。请帮我点菜

  func frameForTabAtIndex(index: Int) -> CGRect {
    guard let tabBarSubviews = tabBarController?.tabBar.subviews else {
      return CGRect.zero
    }
    var allItems = [UIView]()
    for tabBarItem in tabBarSubviews {
      if tabBarItem.isKind(of: NSClassFromString("UITabBarButton")!) {
        allItems.append(tabBarItem)
      }
    }

    let item = allItems[index]
    return item.superview!.convert(item.frame, to: view)
  }



 - 0 : <_UIBarBackground: 0x7ff96060ccb0; frame = (0 0; 414 49); userInteractionEnabled = NO; layer = <CALayer: 0x6040000395a0>>
  - 1 : <UITabBarButton: 0x7ff96060a4b0; frame = (106 1; 99 48); alpha = 0.25; opaque = NO; layer = <CALayer: 0x604000039da0>>
  - 2 : <UITabBarButton: 0x7ff96060bb90; frame = (209 1; 100 48); alpha = 0.25; opaque = NO; layer = <CALayer: 0x604000039bc0>>
  - 3 : <UITabBarButton: 0x7ff96060c420; frame = (313 1; 99 48); opaque = NO; layer = <CALayer: 0x604000039ae0>>
  - 4 : <UITabBarButton: 0x7ff961b39160; frame = (2 1; 100 48); alpha = 0.25; opaque = NO; layer = <CALayer: 0x60c000229f80>>

1 个答案:

答案 0 :(得分:0)

您可以对数组 allItems 进行如下排序:

 allItems.sort { $0.frame.origin.x < $1.frame.origin.x }

这将为您提供排序后的数组,并且它是可变的,因此它将按照UITabBarButton的 x 值对对象进行排序

在代码上方,您将从数组中获取项目。

 let item = allItems[index]

希望有帮助