Ios UIImageView不遵循我应用的约束
我有一位家长,名叫Ios UIImageView不遵循我应用的约束,ios,swift,Ios,Swift,我有一位家长,名叫infoView。它有两个子项:subLabel和tinyImageView。我希望这两个孩子的大小都是30.0,首先是子标签,然后是10像素填充,然后是tinyImageView 出于某种原因,我的tinyImageView没有考虑我在下面提出的任何约束。即使高度/宽度也不受尊重 let boxSize = infoView.frame.size.height //30 let subLabel = UILabel() subLabel.frame = CGRectMake(
infoView
。它有两个子项:subLabel
和tinyImageView
。我希望这两个孩子的大小都是30.0,首先是子标签,然后是10像素填充,然后是tinyImageView
出于某种原因,我的tinyImageView没有考虑我在下面提出的任何约束。即使高度/宽度也不受尊重
let boxSize = infoView.frame.size.height //30
let subLabel = UILabel()
subLabel.frame = CGRectMake(0, 0, boxSize, boxSize)
subLabel.layer.cornerRadius = 5.0
subLabel.clipsToBounds = true
subLabel.backgroundColor = logoColor(1)
subLabel.text = String(post.subscribers)
subLabel.font = UIFont(name: "Lato-Bold", size: 13.0)
subLabel.textColor = UIColor.whiteColor()
subLabel.textAlignment = .Center
infoView.addSubview(subLabel)
//Image
let tinyImageView = UIImageView(image:UIImage(named: "MO.jpg"))
tinyImageView.layer.cornerRadius = 2.5
tinyImageView.clipsToBounds = true
infoView.addSubview(tinyImageView)
let widthConstraint = NSLayoutConstraint(item: tinyImageView, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: boxSize)
tinyImageView.addConstraint(widthConstraint)
let heightConstraint = NSLayoutConstraint(item: tinyImageView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: boxSize)
tinyImageView.addConstraint(heightConstraint)
print("------------")
let horizontalConstraint = NSLayoutConstraint(item: subLabel, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: tinyImageView, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 10)
infoView.addConstraint(horizontalConstraint)
let verticalConstraint = NSLayoutConstraint(item: subLabel, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: tinyImageView, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0)
verticalConstraint.active = true
图像太大了,水平/垂直约束根本不起作用。当前,图像与子标签重叠,就好像它是在没有任何约束的情况下添加的一样。正如@Paulw11在注释中所述,对于以编程方式创建的视图,需要将
translatesAutoResizezingMaskintoConstraints
设置为false
。此外,约束将调整UIImageView
的帧大小,但不会缩放图像。为此,您需要设置contentMode
属性:
tinyImageView.translatesAutoResizingMaskIntoConstraints = false
tinyImageView.contentMode = .ScaleToFill
值,您可能需要考虑<代码> CordNoMe/<代码> >代码> ScaleToFill < /Cord>(缩放以适应区域扭曲纵横比,如果需要),
verticalConstraint的一个激活
激活您添加的所有约束
如果您的约束发生冲突,
将translatesAutoResizengMaskintoConstraints
设置为false
(通常,如果以编程方式设置约束,则将其设置为false)对于以编程方式创建的视图,必须将其translatesAutoResizengMaskintoContracts
属性显式设置为false,才能正确应用约束