【问题标题】:addSubview SwiftUI View to UIKit UIView in Swift在 Swift 中将 SwiftUI 视图添加到 UIKit UIView
【发布时间】:2019-10-31 01:57:37
【问题描述】:

我已尝试将addSubview SwiftUI 视图转换为 UIView。 self.view.addSubview(contentView)

错误:无法将“ContentView”类型的值转换为预期的参数类型 'UIView'

请帮我实现这个 UI。

import UIKit
import SwiftUI

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        view.backgroundColor = UIColor.lightGray
        
        let contentView = ContentView()
        view.addSubview(contentView) // Error: Cannot convert value of type 'ContentView' to expected argument type 'UIView'
    }


}


struct ContentView: View {
    var body: some  View {
        Text("Hello world")
    }
    
}

【问题讨论】:

  • View 协议 != 一个UIView
  • 观看第 231 节的非常第一部分:集成 SwiftUI。您需要使用UIHostingControllerdeveloper.apple.com/videos/play/wwdc2019/231
  • 抱歉第二条评论。由于UIHostingController is a UIViewController` 您希望使用addSubview,您还需要学习如何使用子视图控制器(在UIKit 中完成),其中一部分涉及添加视图作为父视图的子视图。宿主控制器(一个用于 UIKit、AppKit 和 WatchKit)是完整的控制器,并且很容易用于 全屏 SwiftUI 视图。希望这会有所帮助。

标签: uikit swiftui xcode11 ios13


【解决方案1】:

第 1 步: 使用 SwiftUI View 创建 UIHostingController 的实例

struct ContentView : View {
    var body: some View {
        VStack {
            Text("Test")
            Text("Test2")

        }
    }
}

var child = UIHostingController(rootView: ContentView())

第 2 步: 将 UIHostingController 的实例作为子视图控制器添加到 Any UIKit ViewController

var parent = UIViewController()
child.view.translatesAutoresizingMaskIntoConstraints = false
child.view.frame = parent.view.bounds
// First, add the view of the child to the view of the parent
parent.view.addSubview(child.view)
// Then, add the child to the parent
parent.addChild(child)

您可以使用以下代码删除子控制器 从视图控制器中移除

// Then, remove the child from its parent
child.removeFromParent()

// Finally, remove the child’s view from the parent’s
child.view.removeFromSuperview()

【讨论】:

  • 感谢您的回答,现在我可以在 Mac 状态栏应用程序中使用 SwiftUI。但是,您正在通过父视图设置 SwiftUI 视图的框架。我想反过来做,有没有办法?据我所知,除非尚未设置,否则该孩子的框架将始终为零。
  • 这个答案很好,谢谢。我知道 Apple 非常重视“从头开始重写你的应用程序”和“不连接任何第三方代码”。但对于地球上的人们来说,如果 Apple 只是隐蔽地处理上面的所有样板代码,那就太好了。然后我们可以逐步将 UIViews 切换为 Views。
  • 上面没有演示当你想直接从 UIView 使用 SwiftUI 视图时会发生什么(即层次结构深处的 UIView 希望使用现有的 SwiftUI 视图,但它没有可以访问它的 UIViewController)
  • @strangetimes SwiftUI 不支持。您应该考虑重构您的代码,以便您的视图可以访问它们的控制器。
猜你喜欢
  • 2018-09-22
  • 1970-01-01
  • 2016-02-29
  • 1970-01-01
  • 1970-01-01
  • 2019-12-28
  • 2022-07-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多