在 SwiftUIView 中使用来自委托的函数

时间:2021-01-18 16:35:09

标签: ios swift xcode

任何想要帮助菜鸟的人的快速问题。 所以我的主类中有一个协议,它有一个我想从 UIView 访问的函数。这适用于其他视图控制器。但是,在我的准备功能中,我尝试这样做:

        if let destination = segue.destination as? SwiftUIView {
            destination.delegate = self
    }

但我得到,“从‘UIViewController’转换到不相关的类型‘SwiftUIView’总是失败” 和“无法分配给属性:'destination' 是一个 'let' 常量”。

这是我的整个准备功能:

override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
    if segue.destination is ClientView
    {
        let vc = segue.destination as? ClientView
        vc?.username = thetitle;
    }
    if let destination = segue.destination as? CreateClientView {
            destination.delegate = self
    }
    if let destination = segue.destination as? SwiftUIView {
            destination.delegate = self
    }
}

并且它在 CreateClientView 中工作。但不适用于我的 SwiftUIView。知道如何解决这个问题吗?我正在以与在 CreateClientView 中相同的方式访问 SwiftUIView 中的函数。谢谢大家。

SwiftUIView 只是类型 View 并且看起来像这样(删节):

struct SwiftUIView: View {
@State var username: String = ""
@State var address: String = "";
@State var notificationsEnabled: Bool = false
@State var note: String = "";
var delegate:ClientDelegate?;

和 SwiftUIView 是另一个视图的子视图,如下所示:

class CreateClientView: UIViewController {
let contentView = UIHostingController(rootView: SwiftUIView());

var delegate:ClientDelegate?;
var mainView : ViewController?;

override func viewDidLoad() {
    super.viewDidLoad()
    addChild(contentView);
    view.addSubview(contentView.view);
    setupConstraints()
    // Do any additional setup after loading the view.
}

1 个答案:

答案 0 :(得分:0)

如错误消息所述,您正在尝试将 SwiftUI view 转换为 ViewController。你不能。

要快速解决您的问题,您可以试试这个

override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
    if segue.destination is ClientView
    {
        let vc = segue.destination as? ClientView
        vc?.username = thetitle;
    }
    if let destination = segue.destination as? CreateClientView {
            destination.delegate = self
    }
    if let destination = segue.destination as? CreateClientView {
            destination.delegate = self
    }
}

class CreateClientView: UIViewController, SwiftUIViewDelegate  {
let contentView = UIHostingController(rootView: SwiftUIView(delegate: self));

var delegate:ClientDelegate?;
var mainView : ViewController?;

override func viewDidLoad() {
    super.viewDidLoad()
    addChild(contentView);
    view.addSubview(contentView.view);
    setupConstraints()
    // Do any additional setup after loading the view.
}

// 标记:SwiftUIViewDelegate
// 在这里调用 ClientDelegate,只要 SwiftUIViewDelegate 方法被实现
}

protocol SwiftUIViewDelegate {...}

struct SwiftUIView {
 let delegate:  SwiftUIViewDelegate 
}
相关问题