I exploit Swiftui in UIViewController to show the content material. There’s a type in Swiftui. After filling within the type, click on the Run button on the navigation bar of UIViewController to set off the perform execution in Swiftui.
The UIViewController code is as bellow:
import UIKit
import SwiftUI
class TestVC: UIViewController {
var testView1: TestView1?
override func viewDidLoad() {
tremendous.viewDidLoad()
self.setupData()
self.setupUI()
}
func setupData() {
}
func setupUI() {
self.navigationController?.navigationBar.isTranslucent = false
setupNavBar()
let contentView = TestView1()
let hostVC = UIHostingController(rootView: contentView)
guard let hostView = hostVC.view else {
return
}
view.addSubview(hostView)
hostView.body = self.view.body
self.testView1 = contentView
}
func setupNavBar() {
let item1 = UIBarButtonItem(customView: self.runBtn)
navigationItem.rightBarButtonItems = [item1]
}
lazy var runBtn: UIButton = {
let btn = UIButton()
btn.setTitle("Run", for: .regular)
btn.setTitleColor(.blue, for: .regular)
btn.addTarget(self, motion: #selector(runBtnAction), for: .touchUpInside)
return btn
}()
@objc func runBtnAction() {
self.testView1?.run2()
}
}
The SwiftUI view code is as bellow:
import SwiftUI
struct TestView1: View {
@State non-public var inputContent: String = "init"
var physique: some View {
return VStack(spacing: 20) {
ScrollView(showsIndicators: false) {
Button {
run1()
} label: {
Textual content("Run")
.foregroundColor(.blue)
}
TextEditor(textual content: $inputContent)
.foregroundColor(.black)
.background(Colour.grey.opacity(0.2))
}
}
.foregroundColor(.black)
.background(Colour.white)
}
public func run1() {
inputContent = "run take a look at 1"
print("run1 inputContent is (inputContent)")
}
public func run2() {
// inputContent must be "run take a look at 1" however output is "init"
print("run2 earlier than inputContent is (inputContent)")
inputContent = "run take a look at 2"
// inputContent must be "run take a look at 2" however output continues to be "init"
print("run2 after inputContent is (inputContent)")
}
}
First click on “Run” button in SwiftUI, it print “run1 inputContent is run take a look at 1
“, which meets expectations.
Nevertheless, when click on “Run” button in TestVC, it all the time print “run2 inputContent is init
“, not the modified new worth.
How can I accurately name Swiftui’s capabilities in uikit?