Swift -Tabbar 项目框架在将框架转换为窗口时返回有问题的值 [英] Swift -Tabbar item frame is returning questionable value when converting frame to window

查看:28
本文介绍了Swift -Tabbar 项目框架在将框架转换为窗口时返回有问题的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含 5 个项目的 tabBar.要获取第一个 tabBar 项目的框架并根据该框架设置一些东西,我使用了这个完美的作品:

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)

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

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)

但是设置 tabBar.items?[2] 我在 windowRect 中的 336 处得到了正确的 x 坐标>:

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)

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

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

推荐答案

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

这篇关于Swift -Tabbar 项目框架在将框架转换为窗口时返回有问题的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆