Reputation: 2743
I have a webveiw with a youtube video i embedded.It work fine and all but the problem is I want it to be entered and be the size of the width of the web view. Right now it is to the left side and not expanded to the other size. The hight is fine but I want the width fixed.
where player is the uiview Here is what I have so far:
let myVideo = "https://myvideo"
let myHTML = "<iframe width=\"\(player.frame.size.width)\" height=\"\(player.frame.size.height)\" src=\"\(myVideo)?&playsinline=1\" frameborder=\"0\" allowfullscreen></iframe>"
player.allowsInlineMediaPlayback = true
player.loadHTMLString(myHTML, baseURL: nil)
player.frame = UIScreen.mainScreen().bounds
player.backgroundColor = UIColor.clearColor()
player.widthAnchor.constraintEqualToConstant(250)
Thanks for any help with this.
Upvotes: 2
Views: 4181
Reputation: 16987
I would highly recommend you to use https://github.com/youtube/youtube-ios-player-helper, Its official way to do it. Give it try, you don't need to write html and css yourself.
Sample Usage
1) Add pod in your project
pod 'youtube-ios-player-helper'
2) Add UIView
in xib and change its class to YTPlayerView
3) Create IBOutlet for YTPlayerView
@property(nonatomic, strong) IBOutlet YTPlayerView *playerView;
4) In ViewController.m
NSDictionary *playerVars = @{
@"playsinline" : @1,
@"showinfo" : @0,
@"rel" : @0,
@"controls" : @1,
@"origin" : @"https://www.example.com", // this is critical
@"modestbranding" : @1
};
[self.playerView loadWithVideoId:@"Youtube Video Id" playerVars:playerVars];
For complete documentation please visit.
https://github.com/youtube/youtube-ios-player-helper
Upvotes: 3
Reputation: 900
Use align="middle"
complete code below
let myVideo = "https://myvideo"
let myHTML = "<iframe align=\"middle\" width=\"\(player.frame.size.width)\" height=\"\(player.frame.size.height)\" src=\"\(myVideo)?&playsinline=1\" frameborder=\"0\" allowfullscreen></iframe>"
player.allowsInlineMediaPlayback = true
player.loadHTMLString(myHTML, baseURL: nil)
player.frame = UIScreen.mainScreen().bounds
player.backgroundColor = UIColor.clearColor()
player.widthAnchor.constraintEqualToConstant(250)
Upvotes: 1
Reputation: 751
This is what I used in an App to show a YouTube video centered in my UIWebView.
let width: CGFloat = player.frame.size.width
let height = ceil((width / 16) * 9) // Assuming that the videos aspect ratio is 16:9
let htmlString = "<div style='text-align: center;'><script type='text/javascript' src='http://www.youtube.com/iframe_api'></script><script type='text/javascript'>function onYouTubeIframeAPIReady(){ytplayer=new YT.Player('playerId',{events:{onReady:onPlayerReady}})}function onPlayerReady(a){a.target.playVideo();}</script><iframe id='playerId' type='text/html' width='\(width)' height='\(height)' src='http://www.youtube.com/embed/\(youtubeVideoID)?enablejsapi=1&rel=0&playsinline=1&autoplay=1' frameborder='0'></div>"
Upvotes: 1