【发布时间】:2017-08-24 05:52:48
【问题描述】:
class videoCell:UICollectionViewCell
{
override init(frame: CGRect) {
super.init(frame: frame)
setUpViews()
}
let titlelabel : UILabel =
{
var label = UILabel()
label.backgroundColor = UIColor.brown
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
func setUpViews()
{
addSubview(titlelabel)
addConstraint(NSLayoutConstraint(item: titlelabel, attribute:.top, relatedBy: .equal, toItem: thumbNailImageView, attribute: .bottom, multiplier: 1, constant: 8))
addConstraint(NSLayoutConstraint(item: titlelabel, attribute:.left, relatedBy: .equal, toItem: thumbNailImageView, attribute: .right, multiplier: 1, constant: 8))
addConstraint(NSLayoutConstraint(item: titlelabel, attribute: .right, relatedBy: .equal, toItem: thumbNailImageView, attribute: .right, multiplier: 1, constant: 0))
addConstraintsWithFormat(format: "V:[v0(20)]", views:titlelabel)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension UIView
{
func addConstraintsWithFormat(format:String,views:UIView...)
{
var allViews = [String:UIView]()
for data in 0...views.count-1
{
let key = "v\(data)"
allViews[key] = views[data]
}
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: format, options: NSLayoutFormatOptions(), metrics: nil, views: allViews))
}
}
我上面的函数 setUpViews() 没有在视图上呈现我的标签。任何人都可以在这里帮助我。我没有收到任何错误,它编译得很好,但没有输出。
addConstraints 方法有什么问题吗??
请帮忙谢谢。
如果我添加此约束,它会起作用-:
addConstraintsWithFormat(format: "H:|[v0]|", views:titlelabel)
并注释这行代码-:
addConstraint(NSLayoutConstraint(item: titlelabel, attribute:.left, relatedBy: .equal, toItem: thumbNailImageView, attribute: .right, multiplier: 1, constant: 8))
addConstraint(NSLayoutConstraint(item: titlelabel, attribute: .right, relatedBy: .equal, toItem: thumbNailImageView, attribute: .right, multiplier: 1, constant: 0))
但这并没有将我的观点固定在我需要的地方以及我希望它如何工作。
【问题讨论】:
-
我认为这是因为“左约束”的常数为
8而“右约束”的常数为 0。标签的左侧距离右侧 8 个点而右侧在左侧。我对此有点不好,但这应该是原因。将“左约束”的constant更改为-8,它应该会显示出来。 -
@Eendje 还是一样的结果。
-
如果注释掉“左约束”并替换为:
NSLayoutConstraint(item: titleLabel, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 8)?