UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Use a SwiftUI chart in UIKit

Forums > Swift

I have a viewController in a storyboard. In the storyboard I have a section where i'd like to include a SwiftUI chart. I've investigated this and took example code from various sources but it's not working out. The code compiled but i'm not seeing anything in the UI.

When I run the app with the code below I see nothing what so ever in my UI. But it does compile with no errors.

As can be seen the values for the chart are currently hardcoded. That will be replaced with real data once I get the UI to work.

I've been playing with the code, checking blogs etc but as a noob i'm not fully understanding many topics.

Someone told me I need to add constraints after the add subview but even though the code compiles i'm not seeing anything in the UI.

I'm stuck :( I'd appriciate any advice .

// Revenue Chart

        // Create CGSize for a UIKit View and its sub view
        let size = CGSize(width: 400, height: 400)
        let sizeSubView = CGSize(width: 200, height: 200)

        // Create UIKit View
        let uiView = UIView(frame: CGRect(origin: .zero, size: size))
        uiView.backgroundColor = .systemBlue

        // Create a subview to be placed at the centre of above view
        // this will be a container view for the Swift UI View
        let centerPointForSubView = CGRect(origin: CGPoint(x: 100, y: 100), size: sizeSubView)
        let uiViewSubView = UIView(frame: centerPointForSubView)
        uiViewSubView.backgroundColor = .white

        // Add placeholder subview to UIKit View
        uiView.addSubview(uiViewSubView)

        struct Item: Identifiable {
            var id = UUID()
            let type: String
            let value: Double
        }

        struct ContentViewChart: View {
            let items: [Item] = [
                Item(type: "1", value: 100 ),
                Item(type: "2", value: 80 ),
                Item(type: "3", value: 120 ),
                Item(type: "4", value: 20 ),
                Item(type: "5", value: 55 ),
                Item(type: "6", value: 170 ),
                Item(type: "7", value: 20 ),
                Item(type: "8", value: 10 ),
                Item(type: "9", value: 5 ),
                Item(type: "10", value: 1 ),
                Item(type: "11", value: 500 ),
                Item(type: "12", value: 700 )
            ]
            var body: some View {
                NavigationView {
                    ScrollView {

                        Chart(items) { item in
                            LineMark(
                                x: .value("Month", item.type),
                                y: .value("Revenue", item.value)
                            )
                            .foregroundStyle(Color.purple.gradient)
                        }
                        .frame(height: 200)
                        .padding()
                    }
                  //  .navigationTitle("Charts")
                }
            }
        }

        // Create a SwiftUI View
        let swiftUIView = ContentView()

        // Define a hosting VC.
        // A UIKit view controller that manages a SwiftUI view hierarchy.
        let host = UIHostingController(rootView: swiftUIView)
        let hostView = host.view!

        // Add the SwiftUI view to the UIKit view
        uiViewSubView.addSubview(hostView)

        uiViewSubView.translatesAutoresizingMaskIntoConstraints = false
        let horizontalConstraint = NSLayoutConstraint(item: uiViewSubView, attribute: NSLayoutConstraint.Attribute.centerX, relatedBy: NSLayoutConstraint.Relation.equal, toItem: view, attribute: NSLayoutConstraint.Attribute.centerX, multiplier: 1, constant: 0)
        let verticalConstraint = NSLayoutConstraint(item: uiViewSubView, attribute: NSLayoutConstraint.Attribute.centerY, relatedBy: NSLayoutConstraint.Relation.equal, toItem: view, attribute: NSLayoutConstraint.Attribute.centerY, multiplier: 1, constant: 0)
        let widthConstraint = NSLayoutConstraint(item: uiViewSubView, attribute: NSLayoutConstraint.Attribute.width, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 1, constant: 100)
        let heightConstraint = NSLayoutConstraint(item: uiViewSubView, attribute: NSLayoutConstraint.Attribute.height, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 1, constant: 100)

2      

You call the SwiftUI view ContentViewChart but when creating you call ContentView(). That maybe the issue. I assume yoiu have also import Charts

Because the chart displays in a SwiftUI project fine

2      

Hello, thank you for your response. I did change that but no luck. When running the app I do not see my chart sadly. And yes, I am importing charts too.

2      

I got it working with your graph in a UIViewController. Your are having problem either becouse you forgot to add the hostingVC as a child view controller or constraint issue (had hard time following your constraints).

I also moved the swiftUI view into a separate file and renamed it to MyChartsView

        if #available(iOS 16, *) {
            let chartView = MyChartsView()
            let hostingViewController = UIHostingController(rootView: chartView)
            addChild(hostingViewController)

            if let hostView = hostingViewController.view {
                view.addSubview(hostView)
                NSLayoutConstraint.activate([
                    hostView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
                    hostView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
                    hostView.topAnchor.constraint(equalTo: view.topAnchor),
                    hostView.heightAnchor.constraint(equalToConstant: 300)
                ])
            }
        }

2      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.