It's possible to add a second screen to an iOS device, either using an AirPlay with an Apple TV, or by using an AV adapter cable. The iOS simulator also lets us preview the output of the second screen, so testing is easy. This tutorial takes you through the process of adding a label to a second display.
var window: UIWindow?
Apple's implementation of iOS has objects to represent Screens, Windows and Views. A UIWindow has a UIScreen property and it also has a UIView property, so we need to be responsible for creating both the Window and the View.
Within the ViewController class declare two optional properties, a UIWindow and a UIView as follows:var secondWindow : UIWindow?
var secondScreenView : UIView?
The window and view are both optional because the user could remove the screen at anytime, or may not connect one at all.
var externalLabel = UILabel()
@objc func setupScreen(){
if UIScreen.screens.count > 1{
//find the second screen
let secondScreen = UIScreen.screens[1]
//set up a window for the screen using the screens pixel dimensions
secondWindow = UIWindow(frame: secondScreen.bounds)
//windows require a root view controller
let viewcontroller = UIViewController()
secondWindow?.rootViewController = viewcontroller
//tell the window which screen to use
secondWindow?.screen = secondScreen
//set the dimensions for the view for the external screen so it fills the screen
secondScreenView = UIView(frame: secondWindow!.frame)
//add the view to the second screens window
secondWindow?.addSubview(secondScreenView!)
//unhide the window
secondWindow?.isHidden = false
//customised the view
secondScreenView!.backgroundColor = UIColor.white
//configure the label
externalLabel.textAlignment = NSTextAlignment.center
externalLabel.font = UIFont(name: "Helvetica", size: 50.0)
externalLabel.frame = secondScreenView!.bounds
externalLabel.text = "Hello"
//add the label to the view
secondScreenView!.addSubview(externalLabel)
}
}
func registerForScreenNotifications(){
let notificationCentre = NotificationCenter.default
notificationCentre.addObserver(self, selector: #selector(ViewController.setupScreen), name: UIScreen.didConnectNotification, object: nil)
}
viewDidLoad
method, add code to call the two methods you've just created: setupScreen()
registerForScreenNotifications()
An example project can be found on GitHub