Swift -Tabbar item frame is returning questionable value when converting frame to window

我的未来我决定 提交于 2021-01-29 17:22:48

问题


I have a tabBar with 5 items. To get the frame of the first tabBar item and set something based on that frame I use this which works perfectly:

guard let firstTab = tabBarController?.tabBar.items?[0].value(forKey: "view") as? UIView else { return }
        
guard let window = UIApplication.shared.windows.filter({$0.isKeyWindow}).first else { return }

let windowRect = lastTab.convert(firstTab.frame, to: window)

print(firstTab) // (2.0, 1.0, 79.00000000298023, 48.0)
print(windowRect) // (4.0, 689.0, 79.00000000298023, 48.0)

But when I try the above code to get the frame of the 5th tab, the values are incorrect. When setting tabBar.items?[4], the x coordinate of the frame is way off screen at 665 in the windowRect:

guard let lastTab = tabBarControlle?.tabBar.items?[4].value(forKey: "view") as? UIView else { return }

guard let window = UIApplication.shared.windows.filter({$0.isKeyWindow}).first else { return }

let windowRect = lastTab.convert(lastTab.frame, to: window)

print(lastTab) // (332.99999999701976, 1.0, 79.00000000298023, 48.0)
print(windowRect) // (665.9999999940395, 689.0, 79.0000000029803, 48.0)

But setting tabBar.items?[2] I get the correct x coordinate at 336 in the windowRect:

// setting the 2nd item gives me the correct frame for the 4th item
guard let lastTab = tabBarControlle?.tabBar.items?[2].value(forKey: "view") as? UIView else { return }

guard let window = UIApplication.shared.windows.filter({$0.isKeyWindow}).first else { return }

let windowRect = lastTab.convert(lastTab.frame, to: window)

print(lastTab) // (168.00000000596046, 1.0, 77.99999998807907, 48.0)
print(windowRect) // (336.0000000119209, 689.0, 77.99999998807908, 48.0)

Why is tabBar.items?[2] returning the value for tabBar.items?[4] in the window’s frame?


回答1:


You missed .superview.

private func convertTabFrame(for index: Int) -> CGRect? {
    guard let window = UIApplication.shared.windows.first(where: {$0.isKeyWindow}) else { return nil }
    guard let tabView = self.tabBarController?.tabBar.items?[index].value(forKey: "view") as? UIView else { return nil }
    return tabView.superview?.convert(tabView.frame, to: window)
}


来源:https://stackoverflow.com/questions/65365109/swift-tabbar-item-frame-is-returning-questionable-value-when-converting-frame-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!