我正在尝试将一个UIView(红色)的原点和宽度/高度设置为第二个UIView(蓝色)。
我正在调用UIView.frame.origin或size,由于某种原因,y原点不起作用。
我也尝试过使用布局约束(请参见下面的注释),但这覆盖了我的蓝色完全受限视图。
然后,我有一个按钮,可将红色视图设置为侧面动画,以便您可以看到下面的蓝色视图,但是我无法让它们排成一列。下面是我的代码。在界面构建器中,我将两个UIViews都设置为容器。蓝色完全受自动布局约束,红色没有约束。
import UIKit
class ViewController: UIViewController
{
@IBOutlet weak var blueContainer: UIView!
@IBOutlet weak var redContainer: UIView!
@IBOutlet weak var button: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
print(redContainer.frame)
redContainer.frame.origin.x = view.frame.width/2
redContainer.frame.size.width = view.frame.width
//try to line up y with origin and size
redContainer.frame.origin.y = blueContainer.frame.origin.y
redContainer.frame.size.height = blueContainer.frame.size.height
//also tried by using constraints
//redContainer.topAnchor.constraint(equalTo: blueContainer.topAnchor).isActive = true
//redContainer.heightAnchor.constraint(equalTo: blueContainer.heightAnchor).isActive = true
print(redContainer.frame)
}
@IBAction func slideRed(_ sender: Any) {
if redContainer.frame.origin.x == 0 {
UIView.animate(withDuration: 0.5) {
self.redContainer.frame.origin.x = self.view.frame.width/2
}
button.setTitle("Come Back Red!", for: .normal)
} else {
UIView.animate(withDuration: 0.5) {
self.redContainer.frame.origin.x = 0
}
button.setTitle("Go Away Red!", for: .normal)
}
}
}
最佳答案
ViewDidLoad
不保证视图已列出其约束。因此,当blueContainer
的frame
和size
是zero
时,您将看不到对redContainer
的任何影响。您应该使用viewDidLayoutSubviews
从frame
获取正确的size
和blueContainer
。
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
redContainer.frame.origin.x = view.frame.width/2
redContainer.frame.size.width = view.frame.width
//try to line up y with origin and size
redContainer.frame.origin.y = blueContainer.frame.origin.y
redContainer.frame.size.height = blueContainer.frame.size.height
}