This question already has an answer here:

How to set Text View to display text in multiple lines? By default it's 1 line.

struct ContentView : View {
    var body: some View {
         Text("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse est leo, vehicula eu eleifend non, auctor ut arcu")
    }
}

enter image description here

I am slowly converting my project over to SwiftUI. I want to connect my UITabBarController in storyboard to a SwiftUI View.

My understanding is the best way is to use a UIHostingController. I added one to my storyboard, connected it to the TabBar, and added my custom HostingViewController as the custom class to that controller. (This does display under the "more" tab if that matters as all)

I assume I am missing some code here but I am finding mostly snippets lacking proper example. UIHostingController

import Foundation
import UIKit
import SwiftUI

class HseEventHostingVC: UIHostingController<HseView>{

}

I have set this as the class for my UIHostingController in storyboard, which is connected to my tab bar. When I try to run, I get this error.

Fatal error: init(coder:) must be implemented in a subclass and call super.init(coder:, rootView:): file

I followed this simple guide here, this was for pushing a SwiftUI View, but figured it isn't too different in theory.

Here is my SwiftUI View

import SwiftUI

struct HseView: View {
    var body: some View {
        let first = HSECell(name: "Newest Observation", duedate: "2019/10/10", status: "Open", reportedBy: "Carson Skjerdal", reportedDate: "2020/01/01", hseid: "OBS12")

        let hseItems = [first]

        return List(hseItems) {item in

            HseItemRow(hsecell: item)
        }
    }
}

struct HseView_Previews: PreviewProvider {
    static var previews: some View {
        HseView()
    }
}

struct HseItemRow: View{

    var hsecell: HSECell

    var body: some View{
        VStack{
            HStack(){
                Text("\(hsecell.hseid)")
                Text("\(hsecell.name)")
                    .bold()
            }
            Divider()
            HStack{
                VStack(alignment: .leading){
                    Text("Reported Date: ")
                        .bold()
                    Text("Reported By: ")
                        .bold()
                    Text("Status: ")
                        .bold()
                    Text("Due Date:")
                        .bold()
                }
                VStack(alignment: .leading){

                    Text("\(hsecell.reportedDate)")

                    Text("\(hsecell.reportedBy)")

                    Text("\(hsecell.status)")

                    Text("\(hsecell.duedate)")
                }
            }.padding(.trailing)

        }
    }


}

As well my HSECell identifiable struct

import Foundation

struct HSECell: Identifiable{

    var id = UUID()
    var name: String
    var duedate: String
    var status: String
    var reportedBy: String
    var reportedDate: String
    var hseid: String 

}

I had some weird behavior in SwiftUI that I did not understand, and I simplified it to this:


struct ContentView: View {
  @State var name: String = ""

  var body: some View {
    Form {
      VStack {
        Text("Line 1")
        Text("Line 2")
        Text("Line 3")
        Text("Line 4")
        Button(action: {
            print("hello world")
        }) { Text("Print hello world")}
      }
    }
  }
}

This makes the "Line 1" ... "Line 4" texts be part of the "Print hello world" button.

If I remove the VStack in the Form they are not.

I am not sure if this is a bug in SwiftUI or if I am not understanding something that maybe I should try to understand, so: does anybody understand why Line 1 ... Line 4 would be part of the button here?

I'm first in SwiftUI and IOS. I want to use SimpleCheckBox in my SwiftUI.

But I only get

Error:(14, 18) static method 'buildBlock' requires that 'Checkbox' conform to 'View'

This is my code.

var body: some View {
  HStack {
    Checkbox(frame: CGRect(x: 50, y: 50, width: 25, height: 25))
    Text("HelloWorld!")

  }
}

How can I use UIControl in SwiftUI?

enter image description hereMy whole code base is in UIKit. I want to build my action extension module using swiftUI.

As I can add NSExtensionPrincipalClass as the initial entry point to the extension UI. How can I set the initial entry point to a swiftUI content view.

struct ActionExtensionInitialView: View {
    var body: some View {
        Text("Hello, World!")
    }
}

I am learning SwiftUI using apple's official tutorial: https://developer.apple.com/tutorials/swiftui/building-lists-and-navigation

Everything works perfectly until I try to show navigation title on an NavigationView by calling .navigationBarTitle.

I have tried to refresh the live view, restart Xcode, but it still doesn't show up.

here is my code:

import SwiftUI

struct LandmarkList : View {
    var body: some View {
        NavigationView {
            List(landmarkData) { landmark in
                LandmarkRow(landmark: landmark)
            }
        }
        .navigationBarItem(title: Text("Done"))
        .navigationBarTitle(Text("Landmarks"))
    }
}

#if DEBUG
struct LandmarkList_Previews : PreviewProvider {
    static var previews: some View {
        LandmarkList()
    }
}
#endif

The Xcode looks like this: Screenshot

According to the tutorial, it should show the navigation title but it doesn't in my case.

Any idea why? Thanks!

Happy New Year! Hi I'm trying to open a local pdf stored in the bundle from a SwiftUI button push action.

First - Do I even need the UIkit Class ViewController: UIViewController setup?

Second - I did check this out, but couldn't find the one that shows how I can call pdf into view from the swiftUI button push. Open PDF file using swift

Third - I found that I could use UIRepresentable? But wasn't sure how.. https://www.pdftron.com/blog/ios/how-to-add-a-pdf-viewer-using-swiftui/


import SwiftUI
import PDFKit

class ViewController: UIViewController {


 let pdfView = PDFView()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        pdfView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(pdfView)

        pdfView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor).isActive = true
        pdfView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor).isActive = true
        pdfView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
        pdfView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true

    }






}

struct PDFKitView : UIViewRepresentable {

    var url: URL?

    func makeUIView(context: Context) -> UIView {
        let pdfView = PDFView()

        if let url = url {
            pdfView.document = PDFDocument(url: url)
        }

        return pdfView
    }

    func updateUIView(_ uiView: UIView, context: Context) {
        // Empty
    }

}


struct CablesView: View {
   //let path1 = Bundle.main.url(forResource: "012ED9-T1301-20", withExtension: "pdf")

   //let pdfView = PDFView()
    //pdfView.translatesAutoresizingMaskIntoConstraints = false
  //view.addSubview(pdfView)

    var body: some View {



        Form{
            Button(action: {}){
                Text("Family Spec Sheet")

            }

            Button(action: {


            }){





                Text("12F, SM, MIC 250 2.0")

            }
            Button(action: {}){
                Text("MIC 250 2.0")

            }
            Button(action: {}){
                Text("MIC 250 2.0")

            }
        }
       }
   }

   struct CablesView_Previews: PreviewProvider {
       static var previews: some View {
           CablesView()
       }
   }

I am new iOS development, I used storyboards and Interface builder to design my application UI. But now I am seeing that many people are using SwiftUI. I searched about SwiftUI and found some points about it as SwiftUI works seamlessly with new Xcode design tools to keep our code and design perfectly in sync. But I am not able to compare it with Interface builder & Storyboard. What are the advantages & disadvantages of SwiftUI over Interface Builder and storyboards?

This question already has an answer here:

How to pop back from detail view in swiftUI programmatically. I have a Home view and then go to next screen. How to go back with button click action in SwiftUI.

Sometimes, I need to make device-specific adjustments to layouts. For example, I may need to reduce spacing on an iPhone with a smaller screen or increase spacing on the largest screens. With UIKit (and even Interface Builder) it was easy to make layout exceptions for specific size classes. What is the best way to do conditional device-specific layouts with SwiftUI?

I've been scouring the SwiftUI documentation, and haven't found a way to access and use this type of information in layouts.

Below is an example for an Apple Watch app. Per Apple's design guidelines, I'm adding 8.5 points of padding to the left and right on the 40mm Series 4. However, the 44mm should have 9.5 points of padding, and any Apple Watch older than Series 4 should have no padding.

What is the best way to achieve this with SwiftUI?

struct ContentView : View {

    var body: some View {
        HStack {
            Text("Hello World")
        }.padding([.horizontal], 8.5)
    }
}

It might sound like a trivial task but I can't find a proper solution for this problem. Possibly I haven't internalized the "SwiftUI-ish" way of thinking yet.

I have a view with a button. When the view loads, there is a condition (already logged in?) under which the view should directly go to the next view. If the button is clicked, an API call is triggered (login) and if it was successful, the redirect to the next view should also happen.

My attempt was to have a model (ObservableObject) that holds the variable "shouldRedirectToUploadView" which is a PassThroughObject. Once the condition onAppear in the view is met or the button is clicked (and the API call is successful), the variable flips to true and tells the observer to change the view.

Flipping the "shouldRedirectToUploadView" in the model seems to work but I can't make the view re-evaluate that variable so the new view won't open.

Here is my implementation so far:

The model

import SwiftUI
import Combine

class SboSelectorModel: ObservableObject {

    var didChange = PassthroughSubject<Void, Never>()

    var shouldRedirectToUpdateView = false {
        didSet {
            didChange.send()
        }
    }

    func fetch(_ text: String) {
        DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
            self.shouldRedirectToUpdateView = true
        }
    }
}

The view

import SwiftUI

struct SboSelectorView: View {
    @State var text: String = ""
    @ObservedObject var model: SboSelectorModel

    var body: some View {
        return ZStack {
            if (model.shouldRedirectToUpdateView) {
                UpdateView()
            }
            else {
                Button(action: {
                    self.reactOnButtonClick()
                }) {
                    Text("Start")
                }
            }
        }.onAppear(perform: initialActions)
    }

    public func initialActions() {
        self.model.shouldRedirectToUpdateView = true
    }

    private func reactOnButtonClick() {
        self.model.fetch()
    }
}

In good old UIKit I would have just used a ViewController to catch the action of button click and then put the new view on the navigation stack. How would I do it in SwiftUI?

In the above example I would expect the view to load, execute the onAppear() function which executes initialActions() to flip the model variable what would make the view react to that change and present the UploadView. Why doesn't it happen that way?

There are SO examples like Programatically navigate to new view in SwiftUI or Show a new View from Button press Swift UI or How to present a view after a request with URLSession in SwiftUI? that suggest the same procedure. However it does not seem to work for me. Am I missing something?

Thank you in advance!