2016-04-12 22 views
0

私はinfoViewという親を持っています。 2人の子供がいる:subLabeltinyImageView。私はこれらの子どもたちの両方が30.0のサイズになりたいと思っています。最初はsubLabel、続いて10ピクセルのパディング、続いてtinyImageViewです。UIImageViewは適用された制約に従いません

なぜなら、私の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 

画像が大きくなりすぎて、水平/垂直の拘束がまったく機能しません。現時点では、あたかも制約なしで追加されたかのように、画像はsubLabelに重なっています。

+0

制約が正しく適用されるようにする – Paulw11

答えて

0

@ Paulw11はコメントに記載されているとおり、プログラムで作成したビューの場合は、translatesAutoResizingMaskIntoConstraintsfalseに設定する必要があります。また、制約はUIImageViewのフレームのサイズを変更しますが、画像の縮尺は変更されません。そのため、あなたはcontentModeプロパティを設定する必要があります:あなたはおそらくcontentModeのために検討する必要が

tinyImageView.translatesAutoResizingMaskIntoConstraints = false 
tinyImageView.contentMode = .ScaleToFill 

値は.ScaleToFill(必要に応じてスケールがアスペクト比を歪曲領域に合わせて)、.ScaleAspectFit(縦横比を維持し、その一部を残しています必要に応じて透明に表示)と.ScaleAspectFill(必要に応じてアスペクト比を維持し、画像の一部をクリップする)。

0

コードからは、制約verticalConstraintのアクティブ化が1回しか見られませんでした。

アクティブすべての制約を追加します。あなたが明示的にfalseに彼らの `translatesAutoResizingMaskIntoContraints`プロパティを設定する必要があり、プログラムで作成されたビューの場合false

あなたの制約が競合し得た場合、 セットtranslatesAutoResizingMaskIntoConstraints(あなたがプログラム的制約を設定する場合、通常は、あなたがfalseに設定)

関連する問題