2016-06-13 97 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\"