MNM MNM - 1 year ago 91
iOS Question

Center an embedded youtube video in a UIWebview Swift

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()

Thanks for any help with this.


I would highly recommend you to use, 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"         : @"", // this is critical
                              @"modestbranding" : @1

[self.playerView loadWithVideoId:@"Youtube Video Id" playerVars:playerVars];

For complete documentation please visit.