I've tried all the tutorials but I keep failing to add action to a button added programatically.
I've tried adding the functions to viewdidload and viewdidappear but it doesn't work.
class videoPlayer: AVPlayerViewController {
// PROPERTIES
let button = UIButton()
.
.
.
override func viewDidLoad() {
super.viewDidLoad()
print("video controller here!")
//Play the Video
let url = Bundle.main.path(forResource: "v1", ofType: "mp4")!
let player = AVPlayer(url: URL(fileURLWithPath: url))
let playerViewController = AVPlayerViewController()
playerViewController.player = player
self.present(playerViewController, animated: true) {
playerViewController.player!.play()
playerViewController.showsPlaybackControls = false
}
//ADDING CUSTOM UI
button.setTitle("TEST", for: UIControl.State.normal)
button.backgroundColor = UIColor.red
button.sizeToFit()
button.addTarget(self, action: #selector(self.buttonAction(sender: )), for: .touchUpInside)
playerViewController.contentOverlayView?.addSubview(button)
}
// MARK :- Functions
@objc func buttonAction(sender :UIButton) {
print("Button tapped")
}
.
.
.
}
A red button does appear on the top left corner but on clicking nothing happens.
尝试像这样设置框架
button.frame = CGRect(x:20,y:20,width:50,height:50)
I found the problem. While copying some code over I didnt realise I was creating a new avplayercontroller. instead setting self.player = player worked!
Basically The buttons were displaying but their bounding rect was under the newly created avplayercontroller(). It was so stupid of me to create a avplayercontroller in a avplayercontrolview.
let videoURL = Bundle.main.path(forResource: "v1", ofType: "mp4")!
let player = AVPlayer(url: URL(fileURLWithPath: videoURL))
self.player = player
self.showsPlaybackControls = false
self.player?.play()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.