ios - swift換頁 - xcode頁面切換




如何使用swift在Xcode中設置背景圖像? (6)

如何使用swift為Xcode 6中的主視圖控制器設置背景圖像? 我知道您可以在助理編輯器中執行此操作,如下所示:

override func viewDidLoad() {
    super.viewDidLoad()
    view.backgroundColor = UIColor.yellowColor()
}

將背景設置為我的資產文件夾中的圖像的代碼是什麼?


SWIFT 4

view.layer.contents = #imageLiteral(resourceName: "webbg").cgImage

對於Swift 4

let backgroundImage = UIImageView(frame: UIScreen.main.bounds)
backgroundImage.image = UIImage(named: "bg_name.png")
backgroundImage.contentMode = UIViewContentMode.scaleAspectFill
self.view.insertSubview(backgroundImage, at: 0)

在Swift 4.2和Xcode 10中

import UIKit
class SharedClass: NSObject {
    //Shared class instance
    static let sharedInstance = SharedClass()

    //Add background image for view's
    func backgroundImage(view: UIView) {
        let imageView = UIImageView(image: UIImage(named: "iphonebackground")!)//Your image name here
    imageView.frame = CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height)
        view.insertSubview(imageView, at: 0)//To set first of all views in VC
    }

    private override init() {

    }

}

現在在這樣的視圖控制器中調用此函數

SharedClass.sharedInstance.backgroundImage(view: self.view)//This is your view

您也可以嘗試這一點,這實際上是其他海報的先前答案的組合:

    let backgroundImage = UIImageView(frame: UIScreen.main.bounds)
    backgroundImage.image = UIImage(named: "RubberMat")
    backgroundImage.contentMode =  UIViewContentMode.scaleAspectFill
    self.view.insertSubview(backgroundImage, at: 0)

override func viewDidLoad() {

    let backgroundImage = UIImageView(frame: UIScreen.main.bounds)
    backgroundImage.image = UIImage(named: "bg_image")
    backgroundImage.contentMode = UIViewContentMode.scaleAspectfill
    self.view.insertSubview(backgroundImage, at: 0)

}

override func viewDidLoad() {
    super.viewDidLoad()
    self.view.backgroundColor = UIColor(patternImage: UIImage(named: "background.png"))
}




background