Swift - 以编程方式刷新约束
我的 VC 以 stackView
开头,并附有 Align Bottom to Safe Area
.
My VC starts with stackView
attached with Align Bottom to Safe Area
.
我有tabBar,但一开始是隐藏的tabBar.isHidden = true
.
I have tabBar, but in the beginning is hidden tabBar.isHidden = true
.
稍后当tabBar出现时,它隐藏了stackView
Later when the tabBar appears, it hides the stackView
所以我需要在 tabBar.isHidden = false
当我使用 tabBar.isHidden = false
启动应用程序时,stackView
会正确显示.
When I start the app with tabBar.isHidden = false
the stackView
is shown properly.
尝试了每个函数,例如:stackView.needsUpdateConstraints() , updateConstraints() , setNeedsUpdateConstraints()
没有成功.
Tried with every function like: stackView.needsUpdateConstraints() , updateConstraints() , setNeedsUpdateConstraints()
without success.
现在我正在以编程方式更改底部,但是当我切换 tabBarIndex 并返回到更改了底部约束的那个时,它会检测到 tabBar 并在另一个视图(未附加约束)下提升 stackView.喜欢再次刷新约束.我正在隐藏和显示此 stackView 并限制屏幕开/关.
Now I'm changing the bottom programatically, but when I switch the tabBarIndex and return to that one with changed bottom constraints it detects the tabBar and lifts the stackView under another view (which is not attached with constraints). Like is refreshing again the constraints. I'm hiding and showing this stackView with constrains on/off screen.
我需要在 tabBar.isHidden = false 之后刷新约束,但约束没有检测到 tabBar 的外观.
I need to refresh constraints after tabBar.isHidden = false, but the constraints don't detect the appearance of the tabBar.
正如我提到在 tabBars 之间切换修复了这个问题,所以一些代码在切换后执行以检测 tabBar.有人知道这个代码吗?我尝试调用方法 viewDidLayoutSubviews 和 viewWillLayoutSubviews 没有成功...有什么建议吗?
As I mention switching between tabBars fixes the issue, so some code executes to detecting tabBar after the switch. Is anyone know this code? I tried with calling the methods viewDidLayoutSubviews and viewWillLayoutSubviews without success... Any suggestions?
这种业余方法修复了我的错误... :D
This amateur approach fixed my bug... :D
tabBarController!.selectedIndex = 1
tabBarController!.selectedIndex = 0
或者带有扩展名
Or with an extension
extension UITabBarController {
// Basically just toggles the tabs to fix layout issues
func forceConstraintRefresh() {
// Get the indices we need
let prevIndex = selectedIndex
var newIndex = 0
// Find an unused index
let items = viewControllers ?? []
find: for i in 0..<items.count {
if (i != prevIndex) {
newIndex = i
break find
}
}
// Toggle the tabs
selectedIndex = newIndex
selectedIndex = prevIndex
}
}
用法(在切换暗/亮模式时调用):
Usage (called when switching dark / light mode):
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
tabBarController?.forceConstraintRefresh()
}