【发布时间】:2020-06-11 21:45:21
【问题描述】:
我觉得这很容易完成,但我似乎无法弄清楚。对于不使用情节提要并尝试学习如何以编程方式为我的视图设置约束,我还很陌生。我在情节提要中轻松创建了我想要的视图,但似乎无法以编程方式获得它。
我有我的视图控制器有我的父视图,然后我调用一个容器视图。我想在容器视图中是我设置约束的地方,但每次更改到不同的设备时,我都无法让视图的高度保持不变
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
var clariView = ClariContainerView()
view.addSubview(clariView)
}
}
这是我的视图控制器,然后我的 ClariContainerView 如下所示:
class ClariContainerView: UIView {
lazy var clariQuestionView: UIView = {
let containerView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 0))
containerView.backgroundColor = .blue
containerView.translatesAutoresizingMaskIntoConstraints = false
return containerView
}()
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setupView()
}
public func setupView() {
addSubview(clariQuestionView)
setupLayout()
}
public func setupLayout() {
NSLayoutConstraint.activate([
clariQuestionView.heightAnchor.constraint(equalToConstant: 169)
])
}
}
我需要蓝色视图的高度始终为 169。
【问题讨论】:
-
我建议你使用 Interface Builder 和 Autolayout - 它们更容易使用,而且信息更难在代码中丢失。
-
我希望可以,但我的工作是尽量避免使用故事板和 xibs
标签: swift xcode view uiview constraints