Swift-在将框架转换为窗口时,Tabbar项框架返回了有问题的值



我有一个包含5项的tabBar。为了获得第一个tabBar项目的框架,并根据该框架设置一些东西,我使用了这个完美的方法:

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)

但是当我尝试上面的代码来获得第5个选项卡的框架时,值是不正确的。设置tabBar.items?[4]时,帧的x坐标在windowRect:中的665处远离屏幕

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)

但设置tabBar.items?[2]时,我会在窗口Rect中的336处获得正确的x坐标:

// 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)

为什么tabBar.items?[2]在窗口的帧中返回tabBar.items?[4]的值?

您错过了.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)
}

最新更新