![](/img/trans.png)
[英]How to place a SwiftUI view on top of a UIKit (UIViewRepresentable) view? (bug or mistake?)
[英]How to know swiftUI event in UIKit view controller? || How to provide communication between swiftUI and uikit
我是 swiftUI 的新手。 我想在我當前的 UIkit 項目中添加 swiftUI 視圖,我為此創建了一個演示,我現在卡在其中。
這是我的代碼中的 ViewController:
import UIKit
import SwiftUI
class ViewController: UIViewController {
@IBOutlet weak var stepperContenerView: UIView!
@IBOutlet weak var btn:UIButton!
lazy var stepView = StepperView(intialCount: 1)
lazy var swiftUIHostingView = UIHostingController(rootView: stepView)
override func viewDidLoad() {
super.viewDidLoad()
stepperContenerView.addSubview(swiftUIHostingView.view)
addChild(swiftUIHostingView)
// stepView.delegate = self
swiftUIHostingView.view.frame = stepperContenerView.bounds
stepperContenerView.addConstrained(subview: swiftUIHostingView.view)
swiftUIHostingView.didMove(toParent: self)
}
@IBAction func onClickBtn(_ sender: UIButton) {
let alert = UIAlertController(title: "Stepper count", message: "Current value : \(stepView.getCount())", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "ok", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
//extension ViewController:OnClickStepperButton {
// func updateCount(count: Int) {
// print("Test")
// lbl.text = "Stepper count is - \(count)"
// }
//}
這是我的 swiftUI 步進視圖代碼:-
import SwiftUI
protocol OnClickStepperButton {
func updateCount(count:Int)
}
struct StepperView: View {
@State private var count:Int = 1
var delegate:OnClickStepperButton?
init(intialCount:Int){
self.count = intialCount
}
var body: some View {
HStack(alignment: .center, spacing: 10) {
Button("+", action: {
count += 1
print(count)
// delegate?.updateCount(count: count)
})
Text("\(count)")
.frame(minWidth: 40,minHeight: 40)
.background(Color.white)
.foregroundColor(.black)
.scaledToFill()
Button("-", action: {
if count > 1 {
count -= 1
print(count)
}
// delegate?.updateCount(count: count)
})
}
.font(.system(size: 22, weight: .medium, design: .serif))
.frame(minWidth: 120, minHeight: 40, alignment: .center)
.background(Color.blue)
.foregroundColor(Color.white)
.cornerRadius(20)
}
public func getCount() -> Int {
count
}
}
struct Stepper_Previews: PreviewProvider {
static var previews: some View {
StepperView(intialCount: 1)
.previewLayout(.fixed(width: 300, height: 70))
}
}
代表都沒有調用,我也沒有在單擊按鈕時獲得更新值。 (代表發表評論的目的是為了強調它不起作用,請取消評論以進行檢查)。
delegate
變量永遠不會按原樣設置。
你需要刪除嗎? 從 SwiftUI 視圖中的變量,因此您必須在初始化時提供一個值。
此外,刪除自定義初始化程序。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.