2014-11-16 66 views
1

我想以編程方式實現UIImageView,但它運行得不像我應用自動佈局約束時的預期。爲了簡單起見,我將圖像視圖的框架設置爲100 x 100.這很好,但是一旦我添加了自動佈局約束,框架大小就不再受到尊重,並且圖像以其全尺寸呈現(在這種情況下,320px寬)而不是縮小以適應圖像視圖框。與UIImageView使用自動佈局不保留框架大小

這是爲什麼,我該如何獲得所需的行爲?我想要一個100x100的圖像視圖,可以根據高寬比縮放圖像,並且位於屏幕中央的底部50。

let imageView = UIImageView(frame: CGRectMake(0, 0, 100, 100)) 
imageView.image = UIImage(named: "myimg") 
imageView.contentMode = .ScaleAspectFit 
imageView.clipsToBounds = true 
imageView.setTranslatesAutoresizingMaskIntoConstraints(false) 
self.view.addSubview(imageView) 
self.view.addConstraint(NSLayoutConstraint(item: imageView, attribute: .Bottom, relatedBy: .Equal, toItem: self.view, attribute: .Bottom, multiplier: 1, constant: -50)) 
self.view.addConstraint(NSLayoutConstraint(item: imageView, attribute: .CenterX, relatedBy: .Equal, toItem: self.view, attribute: .CenterX, multiplier: 1, constant: 0)) 

回答

6

使用自動佈局時,不應設置任何框架。您需要爲圖像視圖的寬度和高度再添加兩個約束。

let imageView = UIImageView() 
// your other code here 

imageView.addConstraint(NSLayoutConstraint(item: imageView, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 100)) 

imageView.addConstraint(NSLayoutConstraint(item: imageView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 100)) 
相關問題