如何使用Swift在Xcode中设置背景图片?

如何在Xcode 6中使用swift为我的主视图控制器设置背景图像? 我知道你可以在助理编辑中做到这一点,如下所示:

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

什么是代码来设置我的资产文件夹中的图像的背景?

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

我是iOS开发的初学者,所以我想分享我在本节中获得的全部信息。

首先从图像资源(images.xcassets)创build图像集。

根据文档,这里是所有尺寸需要创build背景图片。

 For iPhone 5: 640 x 1136 For iPhone 6: 750 x 1334 (@2x) for portrait 1334 x 750 (@2x) for landscape For iPhone 6 Plus: 1242 x 2208 (@3x) for portrait 2208 x 1242 (@3x) for landscape iPhone 4s (@2x) 640 x 960 iPad and iPad mini (@2x) 1536 x 2048 (portrait) 2048 x 1536 (landscape) iPad 2 and iPad mini (@1x) 768 x 1024 (portrait) 1024 x 768 (landscape) iPad Pro (@2x) 2048 x 2732 (portrait) 2732 x 2048 (landscape) 

调用图像背景我们可以通过使用这个方法调用图像资源的图像UIImage(named: "background")这里是完整的代码示例

  override func viewDidLoad() { super.viewDidLoad() assignbackground() // Do any additional setup after loading the view. } func assignbackground(){ let background = UIImage(named: "background") var imageView : UIImageView! imageView = UIImageView(frame: view.bounds) imageView.contentMode = UIViewContentMode.ScaleAspectFill imageView.clipsToBounds = true imageView.image = background imageView.center = view.center view.addSubview(imageView) self.view.sendSubviewToBack(imageView) } 
 override func viewDidLoad() { let backgroundImage = UIImageView(frame: UIScreen.main.bounds) backgroundImage.image = UIImage(named: "bg_image") self.view.insertSubview(backgroundImage, at: 0) } 

你也可以试试这个,这是其他海报以前答案的组合:

  let backgroundImage = UIImageView(frame: UIScreen.main.bounds) backgroundImage.image = UIImage(named: "RubberMat") backgroundImage.contentMode = UIViewContentMode.scaleAspectFill self.view.insertSubview(backgroundImage, at: 0) 
  view.layer.contents = #imageLiteral(resourceName: "webbg").cgImage