我是 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))
}
}
委托既沒有呼叫,也沒有在單擊按鈕時獲取更新值。(代表有意發表評論以突出其不起作用,請取消對其進行檢查)。
uj5u.com熱心網友回復:
該delegate變數永遠不會被設定為IS。
您需要洗掉 ? 來自 SwiftUI 視圖中的變數,因此您必須在 init 時提供一個值。
此外,洗掉自定義初始值設定項。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/375489.html
