[英]Center image and add background in swift
所以我有一個屏幕,當應用程序在最近屏幕上時呈現。 但問題是,它位於左上角,我無法將其與中心對齊,也無法將背景設置為白色。 白色背景必須覆蓋屏幕,此圖像應位於中間。 到目前為止,我已經設法添加了圖像。 但在那之后沒有運氣。 任何幫助,將不勝感激。
override func applicationWillResignActive(_ application: UIApplication) {
if let view = self.window.rootViewController?.view.subviews.first(where: {$0.tag == TAG_BLUR_VIEW}){
view.removeFromSuperview()
blurView = nil
}
if blurView == nil{
blurView = UIImageView(image: UIImage(named: "splash.jpg"))
blurView?.backgroundColor = UIColor .white
blurView?.tag = TAG_BLUR_VIEW
}
self.window.rootViewController?.view.insertSubview(blurView!, at: 0)
}
最簡單的解決方案是使用中心 position。
if blurView == nil {
let centerPos = self.window?.rootViewController?.view.center ?? .zero
blurView?.center = centerPos
self.window?.rootViewController?.view.addSubview(blurView!)
}
So the final code snippet based on the provided code is like the following.
override func applicationWillResignActive(_ application: UIApplication) {
if let view = self.window.rootViewController?.view.subviews.first(where: {$0.tag == TAG_BLUR_VIEW}){
view.removeFromSuperview()
blurView = nil
}
if blurView == nil{
blurView = UIImageView(image: UIImage(named: "splash.jpg"))
blurView?.backgroundColor = UIColor .white
blurView?.tag = TAG_BLUR_VIEW
let centerPos = self.window?.rootViewController?.view.center ?? .zero
blurView?.center = centerPos
}
self.window.rootViewController?.view.insertSubview(blurView!, at: 0)
}
您需要為您的視圖指定約束。
override func viewDidLoad() {
blurView.translatesAutoresizingMaskIntoConstraints = false
blurView.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
// Add the other constraints such as topAnchor, leadingAnchor and trailingAnchor etc...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.