You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中移除WKWebView加载YouTube Shorts的白色边框及优化控制栏

解决YouTube Shorts嵌入的白色边框及控制栏尺寸问题

一、消除白色边框问题

白色边框源于HTML默认边距、固定尺寸的iframe未撑满容器、容器布局逻辑不匹配WKWebView这三个问题,按以下方式修改:

  • 重置HTML的body样式,清除默认边距与内边距
  • 将容器div的高度设为100%(而非100vh,WKWebView的高度并非设备视口高度),使其完全适配WebView空间
  • 移除iframe的固定宽高,改为百分比撑满容器,同时去掉边框

修改后的HTML字符串及相关代码调整如下:

二、解决控制栏尺寸过小问题

控制栏尺寸由YouTube根据iframe实际渲染尺寸自动调整,过小问题多因iframe显示空间不足,可通过两种方式解决:

方法1:强制保持竖屏比例

YouTube Shorts为9:16竖屏比例,给容器添加aspect-ratio: 9/16,确保iframe有足够高度承载正常尺寸的控制栏。

方法2:CSS缩放控制栏

若需在小容器中放大控制栏,可给iframe添加缩放变换,同时设置容器溢出隐藏避免内容外漏。

完整修改代码

import SwiftUI
import WebKit

struct SwiftUIView: View {
    @Environment(\.colorScheme) var colorScheme
    var body: some View {
        VStack{
            YouTubeView(link: "-rHELEJuqkU")
                .frame(maxWidth: .infinity, maxHeight: .infinity) // 让WebView撑满父视图空间
        }
    }
}

struct SwiftUIView_Previews: PreviewProvider {
    static var previews: some View {
        SwiftUIView()
    }
}

struct YouTubeView: UIViewRepresentable {
    let link: String

    func makeUIView(context: Context) -> WKWebView {
        let webConfiguration = WKWebViewConfiguration()
        webConfiguration.allowsInlineMediaPlayback = true
        let webView = WKWebView(frame: .zero, configuration: webConfiguration)
        webView.scrollView.isScrollEnabled = false
        return webView
    }
    
    func updateUIView(_ uiView: WKWebView, context: Context) {
        // 适配明暗模式的背景色(可选)
        let bgColor = context.environment.colorScheme == .dark ? "#000000" : "#ffffff"
        
        let embedHTML = """
            <!DOCTYPE html>
            <html>
            <head>
                <style>
                    body { margin: 0; padding: 0; overflow: hidden; background-color: \(bgColor); }
                    .container { width: 100%; height: 100%; display: flex; justify-content: center; align-items: center; aspect-ratio: 9/16; }
                    iframe { width: 100%; height: 100%; border: none; display: block; }
                </style>
            </head>
            <body>
                <div class="container">
                    <iframe src="https://www.youtube.com/embed/\(link)?controls=1" allowfullscreen="true" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"></iframe>
                </div>
            </body>
            </html>
        """
        uiView.loadHTMLString(embedHTML, baseURL: nil)
    }
}

内容的提问来源于stack exchange,提问作者Ahmed Zaidan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 12:29:55