微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Swift -Tabbar 项目框架在将框架转换为窗口时返回可疑值

如何解决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,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,48.0)
print(windowRect) // (665.9999999940395,79.0000000029803,48.0)

但是设置 tabBar.items?[2] 我在 windowRect 中的 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,77.99999998807907,48.0)
print(windowRect) // (336.0000000119209,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)
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。