Last active
January 7, 2020 11:03
-
-
Save florianldt/3ba7d3926f310edda112004e223fde77 to your computer and use it in GitHub Desktop.
Gist trying to answer a Swift Korea (Facebook Group) question.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
import PlaygroundSupport | |
import AVFoundation | |
class PlayerViewController: UIViewController { | |
enum Settings { | |
static let screenW: CGFloat = 375 // For playground use only | |
static let playerHeight: CGFloat = Settings.screenW * (9/16) | |
static let videoUrl = URL(string: "https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4")! | |
} | |
let playerView: UIView = { | |
let view = UIView() | |
view.translatesAutoresizingMaskIntoConstraints = false | |
view.backgroundColor = .green | |
return view | |
}() | |
let playerLayer: AVPlayerLayer = { | |
let layer = AVPlayerLayer() | |
layer.videoGravity = .resizeAspect | |
return layer | |
}() | |
let button: UIButton = { | |
let button = UIButton() | |
button.translatesAutoresizingMaskIntoConstraints = false | |
button.backgroundColor = .lightGray | |
button.addTarget(self, | |
action: #selector(onButton), | |
for: .touchUpInside) | |
return button | |
}() | |
let player = AVPlayer(url: Settings.videoUrl) | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
view.backgroundColor = .red | |
view.addSubview(playerView) | |
view.addSubview(button) | |
setupPlayerView() | |
NSLayoutConstraint.activate([ | |
button.bottomAnchor.constraint(equalTo: view.bottomAnchor), | |
button.rightAnchor.constraint(equalTo: view.rightAnchor), | |
button.leftAnchor.constraint(equalTo: view.leftAnchor), | |
button.heightAnchor.constraint(equalToConstant: 50), | |
]) | |
player.play() | |
} | |
private func setupPlayerView() { | |
NSLayoutConstraint.activate([ | |
playerView.topAnchor.constraint(equalTo: view.topAnchor), | |
playerView.leftAnchor.constraint(equalTo: view.leftAnchor), | |
playerView.rightAnchor.constraint(equalTo: view.rightAnchor), | |
playerView.heightAnchor.constraint(equalToConstant: Settings.playerHeight), | |
]) | |
playerView.layer.addSublayer(playerLayer) | |
playerLayer.player = player | |
} | |
override func viewDidLayoutSubviews() { | |
super.viewDidLayoutSubviews() | |
playerLayer.frame = playerView.bounds | |
} | |
@objc | |
private func onButton() { | |
print("onButton()") | |
} | |
} | |
let viewController = PlayerViewController() | |
PlaygroundPage.current.liveView = viewController |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment