swift - 无法分配给属性:“self”在 UIViewControllerRepresentable 中是不可变的
问题描述
我有以下代码片段:
struct player : UIViewControllerRepresentable {
var url : String
var player1: AVPlayer
func makeUIViewController(context: UIViewControllerRepresentableContext<player>) -> AVPlayerViewController {
let controller = AVPlayerViewController()
player1 = AVPlayer(url: URL(string: url)!)
controller.player = player1
return controller
}
func updateUIViewController(_ uiViewController: AVPlayerViewController, context: UIViewControllerRepresentableContext<player>) {
}
func pause() {
player1.pause()
}
}
这给出了错误:
'不能分配给属性:'self' 是不可变的'
我需要在 makeUIViewController 函数之外拥有 AVPlayer,因为我需要从 pause 函数中访问它。我怎样才能做到这一点?
解决方案
您看到的错误是由于结构是值类型,并且它们上的任何更改其属性的方法都需要标记为mutating
. 不幸的是,您无法标记makeUIViewController
,因为它是在UIViewControllerRepresentable
协议中定义的,但是有一个相当简单的解决方案。
您实际上只使用 url 来构造一个AVPlayer
- 没有必要坚持它。为您的结构编写和初始化程序,该结构接受一个 url 字符串并构造一个AVPlayer
. 我将AVPlayer
可选作为URL(string: String)
返回一个Optional URL
(您可以想象并非所有字符串都是有效的 url)。以下代码按预期工作:
struct Player: UIViewControllerRepresentable {
var player1: AVPlayer?
public init(url string: String) {
guard let url = URL(string: string) else {
self.player1 = nil
return
}
self.player1 = AVPlayer(url: url)
}
func makeUIViewController(context: UIViewControllerRepresentableContext<Player>) -> AVPlayerViewController {
let controller = AVPlayerViewController()
controller.player = player1
return controller
}
func updateUIViewController(_ uiViewController: AVPlayerViewController,
context: UIViewControllerRepresentableContext<Player>) {}
func pause() {
player1?.pause()
}
}
附注:Swift 中的所有类型名称(类、结构、枚举)按照惯例都是大写的:你的结构应该被称为Player
not player
。您还应该考虑Cordinator
-UIViewControllerRepresentable
您需要一些东西来充当您的AVPlayerViewControllerDelegate
.
推荐阅读
- solr - Solr 为每个字母更改返回不同的结果
- tfs - 如何将 WIT 从一个集合迁移到另一个集合?
- android - 如何从 datepickerdialog 中获取值
- sql - SQL:从第一次出现到接下来的五分钟计算某个值的出现次数,并为下一次出现重复相同的值
- c++ - 用空白填充二维数组(来自文件的输入)
- c# - 将图像转换为二进制以存储在 asp.net 的数据库中
- java - 有什么方法可以屏蔽在运行时进入 jText 区域的值
- python - Tornado RequestHandler 参数化
- python - 使用请求使 Raspberry Pi 自动将文件上传到服务器
- list - 尝试在 Future 上使用数组方法“折叠”
- 获取商品的总价