Swift -Tabbar 项目框架在将框架转换为 window 时返回有问题的值

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

我有一个包含 5 个项目的 tabBar。要获取第一个 tabBar 项目的框架并根据该框架设置一些东西,我使用这个非常有效:

guard let firstTab = tabBarController?.tabBar.items?[0].value(forKey: "view") as? UIView else { return }
        
guard let window = UIApplication.shared.windows.filter({[=12=].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[=33]中的665处偏离屏幕=]:

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

guard let window = UIApplication.shared.windows.filter({[=13=].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] 我在 [=38] 中的 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({[=14=].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] 在 window 的框架中返回 tabBar.items?[4] 的值?

你错过了 .superview

private func convertTabFrame(for index: Int) -> CGRect? {
    guard let window = UIApplication.shared.windows.first(where: {[=10=].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)
}