[英]How to fill iPhone X Simulator's background programmatically without Storyboards
So I've created a new iOS single view application with no core data, no test and then I deleted Main.storyboard and the launch screen storyboard.所以我创建了一个新的 iOS 单视图应用程序,没有核心数据,没有测试,然后我删除了 Main.storyboard 和启动屏幕故事板。 I want to do as much in code as I can so I can understand what I'm doing (since I'm just learning iOS programming).
我想尽可能多地编写代码,这样我才能理解我在做什么(因为我只是在学习 iOS 编程)。 The thing is, that I just cant fill the whole iPhone X screen with a background image.
问题是,我无法用背景图像填充整个 iPhone X 屏幕。 I've tried this first using storyboards and had no problem whatsoever.
我首先使用故事板尝试过这个,但没有任何问题。 Am I missing something?
我错过了什么吗?
// AppDelegate.swift
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
let mainController = MainController()
window?.rootViewController = mainController
window?.makeKeyAndVisible()
return true
}
}
// MainController.swift
import UIKit
class MainController: UIViewController {
let background: UIImageView = {
let image = UIImageView(image: #imageLiteral(resourceName: "bg"))
image.translatesAutoresizingMaskIntoConstraints = false
return image
}()
}
extension MainController {
override func viewDidLoad() {
super.viewDidLoad()
setupBackground()
}
}
extension MainController {
func setupBackground() {
view.addSubview(background)
NSLayoutConstraint.activate([
background.leadingAnchor.constraint(equalTo: view.leadingAnchor),
background.trailingAnchor.constraint(equalTo: view.trailingAnchor),
background.topAnchor.constraint(equalTo: view.topAnchor),
background.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
}
}
To summarize the comments above, you need to use a launch storyboard in order for iOS to give you a UIScreen that covers the device's full bounds.总结上面的评论,您需要使用启动故事板,以便 iOS 为您提供覆盖设备完整边界的 UIScreen。
If you don't already have a launch storyboard, create one in Xcode 11 via File
> New
> File...
> Launch Screen
.如果您还没有启动故事板,请通过
File
> New
> File...
> Launch Screen
在 Xcode 11 中创建一个。 Then make sure to select that launch storyboard under your app target > General > Launch Screen File.然后确保在您的应用程序目标 > 常规 > 启动屏幕文件下选择该启动故事板。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.