【发布时间】:2019-12-27 22:41:07
【问题描述】:
我有一个这样初始化的视图:
var view: UIView! = {
var perm = UIView()
perm.backgroundColor = UIColor.black
// enable auto layout
perm.translatesAutoresizingMaskIntoConstraints = false
return perm
}()
之后,我将标签作为子视图添加到view。标签初始化如下:
var title: UILabel! = {
let perm = UILabel()
perm.textColor = UIColor.white
perm.numberOfLines = 0
perm.font = UIFont.boldSystemFont(ofSize: 20)
// enable auto layout
perm.translatesAutoresizingMaskIntoConstraints = false
return perm
}()
之后,我以编程方式添加了一些约束。当我运行应用程序时,title 显示在正确的位置,但尚未设置 view 的背景颜色。
编辑
这就是我设置约束的方式:
view.addSubview(title)
view.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
view.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
view.bottomAnchor.constraint(equalTo: image.bottomAnchor).isActive = true
title.leadingAnchor.constraint(equalTo: title.superview!.leadingAnchor, constant: 20).isActive = true
title.trailingAnchor.constraint(equalTo: title.superview!.trailingAnchor, constant: -20).isActive = true
title.bottomAnchor.constraint(equalTo: title.superview!.bottomAnchor, constant: -20).isActive = true
【问题讨论】:
-
展示你如何设置约束
-
我在 :) 中编辑过它们
标签: ios swift uiview nslayoutconstraint