I am new to swiftUI. I want to add swiftUI view in my current UIkit project for which I created a demo in which I m stuck now.
Here is my ViewController in code :
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)"
// }
//}
and here is my code for swiftUI stepper view:-
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))
}
}
Neither the delegate are calling, nor I m getting update value value on clicking of the button. (delegate are comment on purpose for highlighting its not working kindly uncomment it to check).
CodePudding user response:
The delegate
Variable never gets set as is.
You need to remove the ? From the variable in the SwiftUI view so you are forced to provide a value upon init.
Also, remove the custom initializer.