![](/img/trans.png)
[英]How animate UIView height constraint in Swift programmatically without making an IBOutlet?
[英]How can i replace a IBOutlet uiview programmatically with a custom view in swift
它在故事板中有一個replacementView
UIView
作為UIView
@IBOutlet var replacementView: UIView!
連接。
我想用替換replacementView
replacementView = SecondViewController().view
但它不起作用。 有什么問題?
replacementView
只是參考。 您必須更改視圖堆棧中的對象。
您應該保留對replacementView
的父級的引用。 接下來從parentView 中刪除replacementView
並將SecondViewController().view
添加到parentView。
我建議您嘗試將您的SecondViewController().view
添加為replacementView
並添加填充約束。
您還應該記住保留 SecondViewController,否則它可能會在出現之前被解除分配。 閱讀addChildViewController(childController: UIViewController)
UIViewController 方法。
本質上,您需要向要添加的視圖添加約束,然后刪除舊視圖。 假設項目在您的父視圖中按順序排列,這里有一些代碼可以為您執行此操作。
func replaceView(oldView:UIView, newView: UIView, spacingBetweenViews: CGFloat) {
//loop through, find the view, and add a constraint between the next and previous items.
let parentView = oldView.superview ?? UIView()
for (index, subview) in parentView.subviews.enumerated() {
let PREVIOUS_VIEW = index - 1
let NEXT_VIEW = index + 1
if subview == oldView {
if index == 0 {
//if the first view
let constraints = [
parentView.topAnchor.constraint(
equalTo: newView.topAnchor,
constant: spacingBetweenViews),
newView.bottomAnchor.constraint(
equalTo: parentView.subviews[NEXT_VIEW].topAnchor,
constant: spacingBetweenViews)
]
NSLayoutConstraint.activate(constraints)
} else if index == parentView.subviews.count - 1 {
// if the last view
let constraints = [
parentView.subviews[PREVIOUS_VIEW].bottomAnchor.constraint(
equalTo: newView.topAnchor,
constant: spacingBetweenViews),
newView.bottomAnchor.constraint(
equalTo: parentView.bottomAnchor,
constant: spacingBetweenViews)
]
NSLayoutConstraint.activate(constraints)
} else {
let constraints = [
parentView.subviews[PREVIOUS_VIEW].bottomAnchor.constraint(
equalTo: newView.topAnchor,
constant: spacingBetweenViews),
newView.bottomAnchor.constraint(
equalTo: parentView.subviews[NEXT_VIEW].topAnchor,
constant: spacingBetweenViews)
]
NSLayoutConstraint.activate(constraints)
}
parentView.subviews[index].removeFromSuperview()
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.