[英]Issue with UIImageView background in rotation
你好
我正在嘗試將Image用作ViewController的背景,以指導自己找到以這種方式找到的其他帖子:
我創建了以下擴展名:
extension UIView {
func addBackground() {
// screen width and height:
let width = UIScreen.mainScreen().bounds.size.width
let height = UIScreen.mainScreen().bounds.size.height
let imageViewBackground = UIImageView(frame: CGRectMake(0, 0, width, height))
imageViewBackground.image = UIImage(named: "msa_background")
// you can change the content mode:
imageViewBackground.contentMode = UIViewContentMode.ScaleAspectFill
imageViewBackground.clipsToBounds = true
self.addSubview(imageViewBackground)
self.sendSubviewToBack(imageViewBackground)
}
}
我在每個ViewController中使用以下代碼調用此擴展:
override func viewDidLoad() {
super.viewDidLoad()
self.view.addBackground()
}
問題是,當我旋轉屏幕時,背景中的圖像沒有占據ViewController中的所有空間,我檢查了發現的所有可能解決方案,但找不到解決方法。
我真的很感謝你的幫助
您正在將圖像與屏幕的當前幀一起添加,並且永遠不要更改它。 旋轉設備時,它將保持相同的框架。
更改它以使用AutoLayout這樣...
extension UIView {
func addBackground(imageName: String, contentMode: UIViewContentMode) {
let imageViewBackground = UIImageView()
imageViewBackground.image = UIImage(named: imageName)
// you can change the content mode:
imageViewBackground.contentMode = contentMode
imageViewBackground.clipsToBounds = true
imageViewBackground.translatesAutoresizingMaskIntoConstraints = false
self.insertSubview(imageViewBackground, atIndex: 0)
self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("|[imageViewBackground]|",
options: [],
metrics: nil,
views: ["imageViewBackground", imageViewBackground]))
self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[imageViewBackground]|",
options: [],
metrics: nil,
views: ["imageViewBackground": imageViewBackground]))
}
}
然后,無論設備的方向或視圖框架如何變化,自動布局約束都將使圖像視圖適合該視圖。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.