布局约束不起作用 iOS swift
Layout constraints are not working iOS swift
我添加了前导 |拖尾 |顶部 |高度限制但视图不可见。
let view = UIView()
view.backgroundColor = .orange
self.addSubview(view)
NSLayoutConstraint.activate([
view.leadingAnchor.constraint(equalTo: self.leadingAnchor),
view.trailingAnchor.constraint(equalTo: self.trailingAnchor),
view.topAnchor.constraint(equalTo: self.topAnchor, constant: 100),
view.heightAnchor.constraint(equalToConstant: 300)
])
将视图添加为子视图时,您的代码应禁用 translatesAutoresizingMaskIntoConstraints
。这意味着系统不会创建一组约束来复制视图的自动调整掩码指定的行为。
假设您的约束是正确的,您应该会在将 属性 设置为 false 后看到您的视图。
let view = UIView()
view.backgroundColor = .orange
view.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(view)
NSLayoutConstraint.activate([
view.leadingAnchor.constraint(equalTo: self.leadingAnchor),
view.trailingAnchor.constraint(equalTo: self.trailingAnchor),
view.topAnchor.constraint(equalTo: self.topAnchor, constant: 100),
view.heightAnchor.constraint(equalToConstant: 300)
])
我添加了前导 |拖尾 |顶部 |高度限制但视图不可见。
let view = UIView()
view.backgroundColor = .orange
self.addSubview(view)
NSLayoutConstraint.activate([
view.leadingAnchor.constraint(equalTo: self.leadingAnchor),
view.trailingAnchor.constraint(equalTo: self.trailingAnchor),
view.topAnchor.constraint(equalTo: self.topAnchor, constant: 100),
view.heightAnchor.constraint(equalToConstant: 300)
])
将视图添加为子视图时,您的代码应禁用 translatesAutoresizingMaskIntoConstraints
。这意味着系统不会创建一组约束来复制视图的自动调整掩码指定的行为。
假设您的约束是正确的,您应该会在将 属性 设置为 false 后看到您的视图。
let view = UIView()
view.backgroundColor = .orange
view.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(view)
NSLayoutConstraint.activate([
view.leadingAnchor.constraint(equalTo: self.leadingAnchor),
view.trailingAnchor.constraint(equalTo: self.trailingAnchor),
view.topAnchor.constraint(equalTo: self.topAnchor, constant: 100),
view.heightAnchor.constraint(equalToConstant: 300)
])