SwiftUI报错:无法将String.Type转为预期参数类型String
解决方法
你需要给DownloadButton添加一个接收URL的属性,然后在ContentView传入用户输入的地址,最后在按钮点击时把这个URL传给viewModel的方法。具体步骤如下:
第一步:给
DownloadButton添加存储URL的属性
修改你的DownloadButton结构体,新增一个videoURL属性用来接收从ContentView传过来的用户输入:struct DownloadButton: View { @ObservedObject var viewModel: DownloadViewModel let videoURL: String // 新增属性,接收用户输入的URL var body: some View { Button(action: { // 直接传入videoURL,替换原来的String类型占位 viewModel.downloadVideo(url: videoURL) }) { HStack { Image(systemName: "square.and.arrow.down") Text("Download") } .padding(.vertical, 10) .padding(.horizontal, 16) .foregroundColor(.white) .background(Color.blue) .cornerRadius(8) } // 可选:URL为空时禁用按钮,避免无效点击 .disabled(videoURL.isEmpty) } }第二步:在ContentView中传递用户输入的URL
假设你在ContentView里用@State存储用户输入的URL(比如通过TextField获取),调用DownloadButton时把这个值传进去:struct ContentView: View { @State private var inputURL: String = "" @StateObject private var viewModel = DownloadViewModel() // 或用@ObservedObject,根据你的架构调整 var body: some View { VStack { TextField("输入YouTube视频URL", text: $inputURL) .textFieldStyle(.roundedBorder) .padding() // 把inputURL传给DownloadButton DownloadButton(viewModel: viewModel, videoURL: inputURL) } .padding() } }额外提示:
为了更严谨,你可以在调用downloadVideo前校验URL格式,避免无效请求:Button(action: { guard !videoURL.isEmpty, let url = URL(string: videoURL), (url.host == "www.youtube.com" || url.host == "youtu.be") else { // 这里可以提示用户输入无效URL return } viewModel.downloadVideo(url: videoURL) }) { // ...按钮UI }
内容的提问来源于stack exchange,提问作者Grag Tung
相关产品推荐
相关产品推荐

