首页 > 解决方案 > Sharing Boolean Variables In SwiftUI With ViewController Buttons

问题描述

I've been working with swift for only a couple of weeks and I am currently working on a project that involves "liking" items and saving them to a new area. I initially set each item object to have a boolean variable called liked in order to determine whether or not the item has been liked using the like button. Here's what I have so far under the button function, and any help would be appreciated!

  @IBAction func clickYes(_ sender: Any) { //if the item is liked

        self.performSegue(withIdentifier: "toThird", sender: self)

       liked = true

    }

    @IBAction func clickNo(_ sender: Any) {  //if the item isn't liked

        self.performSegue(withIdentifier: "toThird", sender: self)

    }

How might I get the updated liked boolean variable to be updated by the yes button?

EDIT: To be clear, I want to be able to access the liked variable in my SwiftUI content view. Right now I am getting use of unresolved identifier errors.

EDIT: Here's my viewcontroller code

import UIKit

import SwiftUI

//import SDWebImage

import WebKit

import Combine

class secondscreenViewController: UIViewController {

@IBAction func clickYes(_ sender: Any) {

    self.performSegue(withIdentifier: "toThird", sender: self)

   var liked = true

}



@IBAction func clickNo(_ sender: Any) {

    self.performSegue(withIdentifier: "toThird", sender: self)

}



override func viewDidLoad() {



    super.viewDidLoad()

    let frame = CGRect(x: 20, y: 0, width: 400, height: 700)

  let childView = UIHostingController(rootView: ContentView2())

  addChild(childView)

  childView.view.frame = frame

  view.addSubview(childView.view)

  childView.didMove(toParent: self)



}

}

And contentview:

struct ContentView: View {

@ObservedObject var obs = observer()



var body: some View {



    NavigationView{

        List(obs.datas){i in



            Card(image: i.image, name: i.name, weburl: i.webUrl, rating: i.rating)

        }.navigationBarTitle("Restaurants")

    }



}

}

标签: swiftbuttonbooleanswiftuisharing

解决方案


推荐阅读