如何将iFrame的高度和宽度设置为与WKWebView框架相同?

时间:2019-04-11 10:06:36

标签: ios swift iframe youtube-api wkwebview

我为嵌入其中的WKWebView("myPlayer" in below code)动态地指定了iFrame帧的大小,但是youtube视频视图显示了WKWebView的1/3。下面是我的代码和参考图片。

small video in WKWebView

let videoURL:URL = URL(string: "https://www.youtube.com/embed/695PN9xaEhs")!
@IBOutlet weak var myPlayer: WKWebView!
var didLoadVideo = false
var embedVideoHtml:String?
override func viewDidLoad() {
    super.viewDidLoad()
    embedVideoHtml = {
    return """
    <!DOCTYPE html>
    <html>
    <body>
    <!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
    <div id="player"></div>

    <script>
    var tag = document.createElement('script');

    tag.src = "https://www.youtube.com/player_api";
    var firstScriptTag = document.getElementsByTagName('script')[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

    var player;
    function onYouTubeIframeAPIReady() {
    player = new YT.Player('player', {
    playerVars: { 'autoplay': 1, 'controls': 0, 'playsinline': 1 },
    height: '\(myPlayer.frame.height)',
    width: '\(myPlayer.frame.width)',
    videoId: '\(videoURL.lastPathComponent)',
    events: {
    'onReady': onPlayerReady
    }
    });
    }

    function onPlayerReady(event) {
    event.target.playVideo();
    }
    </script>
    </body>
    </html>
    """
}()


}

所以有人知道如何在myPlayer框架中放置youtube视频视图吗?

1 个答案:

答案 0 :(得分:2)

embedVideoHtml之前的<body>中,添加以下代码:

<style>
    * { margin: 0; padding: 0; }
    html, body { width: 100%; height: 100%; }
</style>

,并在播放器参数中更改以下参数:

height: '\(myPlayer.frame.height)',
width: '\(myPlayer.frame.width)',

至:

height: '100%',
width: '100%',

这些更改之后,您的播放器的大小应调整为WKWebView