2016-06-13 98 views
1

我有一个嵌入youtube视频的webveiw,它可以正常工作,但所有问题都是我希望它被输入并且是web视图宽度的大小。现在它在左侧,而不是扩大到其他尺寸。高度很好,但我希望宽度固定。在UIWebview中嵌入一个youtube视频Swift

这里的球员是UIView的 这是我到目前为止有:

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) 

感谢任何与此帮助。

回答

3

我强烈建议您使用https://github.com/youtube/youtube-ios-player-helper,它的官方方式来做到这一点。试一试,你不需要自己编写html和css。

用法示例

1)添加荚项目中的

pod 'youtube-ios-player-helper' 

2)在厦门国际银行加入UIView并改变其类YTPlayerView

3)创建IBOutlet中为YTPlayerView

@property(nonatomic, strong) IBOutlet YTPlayerView *playerView; 

4)在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]; 

有关完整文档,请访问。
https://github.com/youtube/youtube-ios-player-helper

+0

我给你答案,因为这是我一起去的。其他人很近,但没有按照我需要的那样工作。谢谢。你必须做一些与网站上发布的内容略有不同的内容,因为它们只使用objective-c – MNM

+0

考虑在Swift中使用Objective-C。 – Aamir

1

这是我在应用程序中显示以我的UIWebView为中心的YouTube视频。

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>" 
+0

请问这项工作与iOS?或者只是浏览器? – MNM

+0

我在Swift应用程序中使用了它。 –

+0

非常感谢你 – MNM

1

使用下面

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) 
+0

或者你可以用你的路线创建一个外部div,并添加样式为'display:block'的iframe –

+0

非常感谢 – MNM

1

这为我工作align="middle"完整代码:

iframe width=\"100%\" height=\"315\"