Sort UIView subviews x-order based on position in iOS

I need to find UITabBarButton postion, I have implemented on method for gettings all values of tabbutton and passed index. However initial tabbar button getting is unsorted manner in subview. Below is my code. Please help me in this to order

  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 answer

  • answered 2018-07-12 07:49 Bhavin Kansagara

    You can sort the array allItems as follows:

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

    This will give you the sorted array and and as it is mutable, so it will order the objects as per the x value of UITabBarButton

    just above the code, where you are getting the item from the array.

     let item = allItems[index]
    

    Hope it helps