简体   繁体   English

如何使用swift在Xcode中设置背景图像?

[英]How to set a background image in Xcode using swift?

How can I set a background image for my main view controller in Xcode 6 using swift?如何使用 swift 在 Xcode 6 中为我的主视图控制器设置背景图像? I know that you can do this in the assistant editor as below:我知道您可以在助理编辑器中执行此操作,如下所示:

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

What is the code to set the background to an image I have in my assets folder?将背景设置为我的资产文件夹中的图像的代码是什么?

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

I am beginner to iOS development so I would like to share whole info I got in this section.我是 iOS 开发的初学者,所以我想分享我在本节中获得的全部信息。

First from image assets (images.xcassets) create image set .首先从图像资产(images.xcassets)创建图像集。

According to Documentation here is all sizes need to create background image.根据此处的文档,所有尺寸都需要创建背景图像。

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)

call the image background we can call image from image assets by using this method UIImage(named: "background") here is full code example调用图像背景我们可以使用此方法从图像资产调用图像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")
    backgroundImage.contentMode = UIViewContentMode.scaleAspectfill
    self.view.insertSubview(backgroundImage, at: 0)

}

Updated at 20-May-2020: 2020 年 5 月 20 日更新:

The code snippet above doesn't work well after rotating the device.旋转设备后,上面的代码片段无法正常工作。 Here is the solution which can make the image stretch according to the screen size(after rotating):这是可以根据屏幕尺寸(旋转后)使图像拉伸的解决方案:

class ViewController: UIViewController {

    var imageView: UIImageView = {
        let imageView = UIImageView(frame: .zero)
        imageView.image = UIImage(named: "bg_image")
        imageView.contentMode = .scaleToFill
        imageView.translatesAutoresizingMaskIntoConstraints = false
        return imageView
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        view.insertSubview(imageView, at: 0)
        NSLayoutConstraint.activate([
            imageView.topAnchor.constraint(equalTo: view.topAnchor),
            imageView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            imageView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            imageView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
        ])
    }
}

快速 4

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

You can try this as well, which is really a combination of previous answers from other posters here :您也可以尝试此操作,这实际上是此处其他海报的先前答案的组合:

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

For Swift 4对于 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)

Background Image from API in swift 4 (with Kingfisher ) :来自 swift 4 中API 的背景图像(使用Kingfisher ):

import UIKit
import Kingfisher

extension UIView {

func addBackgroundImage(imgUrl: String, placeHolder: String){
    let backgroundImage = UIImageView(frame: self.bounds)
    backgroundImage.kf.setImage(with: URL(string: imgUrl), placeholder: UIImage(named: placeHolder))
    backgroundImage.contentMode = UIViewContentMode.scaleAspectFill
    self.insertSubview(backgroundImage, at: 0)

}
}

Usage:用法:

someview.addBackgroundImage(imgUrl: "yourImgUrl", placeHolder: "placeHolderName")

SWIFT 5 for TableViewController TableViewController 的 SWIFT 5

override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(true)

tableView.backgroundView = UIImageView(image:"image.jpg")
tableView.backgroundView?.contentMode = .scaleToFill
}

Swift 5.3 in XCode 12.2 Playgrounds XCode 12.2 Playgrounds 中的 Swift 5.3

Place the cursor wherever in the code the #insertLiteral would have been in earlier versions.将光标放在代码中#insertLiteral在早期版本中的任何位置。 Select from the top-menu Editor->Insert Image Literal... and navigate to the file.从顶部菜单Editor->Insert Image Literal...并导航到该文件。 Click Open .点击Open

The file is added to a playground Resource folder and will then appear when the playground is run in whichever view it was positioned when selected.该文件被添加到一个Playground Resource 文件夹中,然后当 Playground 在它被选中时所在的任何视图中运行时就会出现。

If a file is already in the playground Bundle, eg in /Resources, it can be dragged directly to the required position in the code (where it will be represented by an icon).如果某个文件已经在 Playground Bundle 中,例如在 /Resources 中,则可以将其直接拖动到代码中所需的位置(它将用图标表示的位置)。

cf.参见Apple help docs give details of this and how to place other colour and file literals. Apple 帮助文档提供了详细信息以及如何放置其他颜色和文件文字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM