All topics

SwiftUI interview questions

8 questions with answers. 15 open jobs in India ask for SwiftUI.

  1. Why doesn't the navigation title show up using SwiftUI?

    .navigationBarTitle() and .navigationBarItem() are modifiers on the View inside of the NavigationView, not on the NavigationView itself:

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

    and if you think about it, this makes sense. As the View within the NavigationView changes, the new View dictates what the title and contents of the navigation bar should be.

    From Stack Overflow: asked by Yiming Dong, answered by vacawama (CC BY-SA 4.0)

  2. Why is an ObservedObject array not updated in my SwiftUI application?

    You can use a struct instead of a class. Because of a struct's value semantics, a change to a person's name is seen as a change to Person struct itself, and this change is also a change to the people array so @Published will send the notification and the View body will be recomputed.

    import Foundation
    import SwiftUI
    import Combine
    struct Person: Identifiable{
        var id: Int
        var name: String
        init(id: Int, name: String){
            self.id = id
            self.name = name
        }
    }
    class Model: ObservableObject{
        @Published var people: [Person]
        init(){
            self.people = [
                Person(id: 1, name:"Javier"),
                Person(id: 2, name:"Juan"),
                Person(id: 3, name:"Pedro"),
                Person(id: 4, name:"Luis")]
        }
    }
    struct ContentView: View {
        @StateObject var model = Model()
        var body: some View {
            VStack{
                ForEach(model.people){ person in
                    Text("\(person.name)")
                }
                Button(action: {
                    self.mypeople.people[0].name="Jaime"
                }) {
                    Text("Add/Change name")
                }
            }
        }
    }
    

    Alternatively (and not recommended), Person is a class, so it is a reference type. When it changes, the People array remains unchanged and so nothing is emitted by the subject. However, you can manually call it, to let it know:

    Button(action: {
        self.mypeople.objectWillChange.send()
        self.mypeople.people[0].name="Jaime"    
    }) {
        Text("Add/Change name")
    }
    

    From Stack Overflow: asked by jarnaez, answered by kontiki (CC BY-SA 4.0)

  3. What enables SwiftUI's DSL?

    As Martin says, if you look at the documentation for VStack's init(alignment:spacing:content:), you can see that the content: parameter has the attribute @ViewBuilder:

    init(alignment: HorizontalAlignment = .center, spacing: Length? = nil,
         @ViewBuilder content: () -> Content)

    This attribute refers to the ViewBuilder type, which if you look at the generated interface, looks like:

    @_functionBuilder public struct ViewBuilder {
        /// Builds an empty view from an block containing no statements, `{ }`.
        public static func buildBlock() -> EmptyView
        /// Passes a single view written as a child view (e..g, `{ Text("Hello") }`)
        /// through unmodified.
        public static func buildBlock(_ content: Content) -> Content 
          where Content : View
    }

    The @_functionBuilder attribute is a part of an unofficial feature called "function builders", which has been pitched on Swift evolution here, and implemented specially for the version of Swift that ships with Xcode 11, allowing it to be used in SwiftUI.

    Marking a type @_functionBuilder allows it to be used as a custom attribute on various declarations such as functions, computed properties and, in this case, parameters of function type. Such annotated declarations use the function builder to transform blocks of code:

    • For annotated functions, the block of code that gets transformed is the implementation.
    • For annotated computed properties, the block of code that gets transformed is the getter.
    • For annotated parameters of function type, the block of code that gets transformed is any closure expression that is passed to it (if any).

    The way in which a function builder transforms code is defined by its implementation of builder methods such as buildBlock, which takes a set of expressions and consolidates them into a single value.

    For example, ViewBuilder implements buildBlock for 1 to 10 View conforming parameters, consolidating multiple views into a single TupleView:

    @available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
    extension ViewBuilder {
        /// Passes a single view written as a child view (e..g, `{ Text("Hello") }`)
        /// through unmodified.
        public static func buildBlock<Content>(_ content: Content)
           -> Content where Content : View
        public static func buildBlock<C0, C1>(_ c0: C0, _ c1: C1) 
          -> TupleView<(C0, C1)> where C0 : View, C1 : View
        public static func buildBlock<C0, C1, C2>(_ c0: C0, _ c1: C1, _ c2: C2)
          -> TupleView<(C0, C1, C2)> where C0 : View, C1 : View, C2 : View
        // ...
    }
    

    This allows a set of view expressions within a closure passed to VStack's initialiser to be transformed into a call to buildBlock that takes the same number of arguments. For example:

    struct ContentView : View {
      var body: some View {
        VStack(alignment: .leading) {
          Text("Hello, World")
          Text("Hello World!")
        }
      }
    }
    

    gets transformed into a call to buildBlock(_:_:):

    Read the rest at the sourceFrom Stack Overflow: asked by fredpi, answered by Hamish (CC BY-SA 4.0)

  4. Is there a method to blur a background in SwiftUI?

    1. The Native SwiftUI way:

    Just add .blur() modifier on anything you need to be blurry like:

    Image("BG")
       .blur(radius: 20)
    

    💡 Note the top and bottom of the view? you can set the opaque parameter to true to get rid of them.

    Note that you can Group multiple views and blur them together.

    2. The Visual Effect View:

    You can bring the prefect UIVisualEffectView from the UIKit:

    VisualEffectView(effect: UIBlurEffect(style: .dark))
    

    With this tiny struct:

    struct VisualEffectView: UIViewRepresentable {
        var effect: UIVisualEffect?
        func makeUIView(context: UIViewRepresentableContext<Self>) -> UIVisualEffectView { UIVisualEffectView() }
        func updateUIView(_ uiView: UIVisualEffectView, context: UIViewRepresentableContext<Self>) { uiView.effect = effect }
    }
    

    3. iOS 15: Materials

    You can use iOS predefined materials with one line code:

    .background(.ultraThinMaterial)
    

    From Stack Overflow: asked by Sonicjet, answered by Mojtaba Hosseini (CC BY-SA 4.0)

  5. SwiftUI text-alignment

    You can do this via the modifier .multilineTextAlignment(.center).

    Text("CENTER")
        .multilineTextAlignment(.center)
    

    Apple Documentation

    From Stack Overflow: asked by inokey, answered by vrwim (CC BY-SA 4.0)

  6. How do I change the background color of a SwiftUI View?

    Screen's Background Color

    (As of Xcode Version 13)

    I'm not sure if the original poster meant the background color of the entire screen or of individual views. So I'll just add this answer which is to set the entire screen's background color.

    Using ZStack

    var body: some View {
        ZStack {
                Color.purple
                    .ignoresSafeArea()
                
                // Your other content here
                // Other layers will respect the safe area edges
        }
    }
    

    I added .ignoresSafeArea() otherwise, it will stop at safe area margins.

    Using Overlay Modifier

    var body: some View {
        Color.purple
            .ignoresSafeArea(.vertical) // Ignore just for the color
            .overlay(
                VStack(spacing: 20) {
                    Text("Overlay").font(.largeTitle)
                    Text("Example").font(.title).foregroundColor(.white)
            })
    }
    

    Note: It's important to keep the .ignoresSafeArea on just the color so your main content isn't ignoring the safe area edges too.

    iOS 15

    iOS 15/Xcode 13 has introduced some changes to the way Styles work with the edges of safe areas.

    From my observation, the rule is: If the style touches the safe area edge, it will bleed into the safe area.

    This gives you more options for setting a background color/style.

    What is a Style?

    A Style can be:

    • Colors
    • Materials (blur effects)
    • Hierarchical views (.secondary, .tertiary, .quaternary)
    • Gradients

    Using Background

    Because the background of the VStack touches the edge of the safe area, the purple color will bleed into the safe area.

    var body: some View {
        VStack {
            Text("Hello, World!")
            Divider()
            Spacer()
        }
        .background(Color.purple)
    }
    

    TabView

    In iOS 15 the TabView is no longer translucent. Meaning the background color will bleed right into it.

    If you want to provide a custom style for your TabView, you can add another Style that touches the bottom safe area edge so that bleeds into your TabView. For example:

    var body: some View {
        TabView {
            VStack {
                Text("Hello, World!")
                Divider()
                Spacer()
                // Bleeds into TabView
                Rectangle()
                    .frame(height: 0)
                    .background(.thinMaterial)
            }
            .background(Color.purple)
            .tabItem {
                Text("Tab 1")
                Image(systemName: "wifi")
            }
        }
    }
    

    NavigationView

    The same thing that happens to TabView will also happen with NavigationView.

    To customize the NavigationView style, add a style that will touch the top safe area edge and it will bleed into the NavigationView:

    var body: some View {
        NavigationView {
            VStack {
                // Bleeds into NavigationView
                Rectangle()
                    .frame(height: 0)
                    .background(.ultraThinMaterial)
                Text("Hello, World!")
                Divider()
                Spacer()
            }
            .background(Color.purple)
            .navigationTitle(Text("Style"))
        }
    }
    

    iOS 17

    Using ContainerRelativeFrame

    The containerRelativeFrame modifier will use the relative size of the container/device. So if it is on the root view, it will use the size of the device.

    VStack {
        Text("Container Relative Frame")
            .font(.title)
    }
    .containerRelativeFrame([.horizontal, .vertical])
    .background(Gradient(colors: [.teal, .cyan, .green]).opacity(0.6))
    

    I'm totally open to other ways of accomplishing this. Leave a comment or edit this answer if you know of other ways.

    From Stack Overflow: asked by jeremyabannister, answered by BigMountainStudio.com (CC BY-SA 4.0)

  7. SwiftUI: How to implement a custom init with @Binding variables

    Argh! You were so close. This is how you do it. You missed a dollar sign (beta 3) or underscore (beta 4), and either self in front of your amount property, or .value after the amount parameter. All these options work:

    You'll see that I removed the @State in includeDecimal, check the explanation at the end.

    This is using the property (put self in front of it):

    struct AmountView : View {
        @Binding var amount: Double
        
        private var includeDecimal = false
        
        init(amount: Binding<Double>) {
            // self.$amount = amount // beta 3
            self._amount = amount // beta 4
            self.includeDecimal = round(self.amount)-self.amount > 0
        }
    }
    

    or using .value after (but without self, because you are using the passed parameter, not the struct's property):

    struct AmountView : View {
        @Binding var amount: Double
        
        private var includeDecimal = false
        
        init(amount: Binding<Double>) {
            // self.$amount = amount // beta 3
            self._amount = amount // beta 4
            self.includeDecimal = round(amount.value)-amount.value > 0
        }
    }
    

    This is the same, but we use different names for the parameter (withAmount) and the property (amount), so you clearly see when you are using each.

    struct AmountView : View {
        @Binding var amount: Double
        
        private var includeDecimal = false
        
        init(withAmount: Binding<Double>) {
            // self.$amount = withAmount // beta 3
            self._amount = withAmount // beta 4
            self.includeDecimal = round(self.amount)-self.amount > 0
        }
    }
    
    struct AmountView : View {
        @Binding var amount: Double
        
        private var includeDecimal = false
        
        init(withAmount: Binding<Double>) {
            // self.$amount = withAmount // beta 3
            self._amount = withAmount // beta 4
            self.includeDecimal = round(withAmount.value)-withAmount.value > 0
        }
    }
    

    Note that .value is not necessary with the property, thanks to the property wrapper (@Binding), which creates the accessors that makes the .value unnecessary. However, with the parameter, there is not such thing and you have to do it explicitly. If you would like to learn more about property wrappers, check the WWDC session 415 - Modern Swift API Design and jump to 23:12.

    As you discovered, modifying the @State variable from the initilizer will throw the following error: Thread 1: Fatal error: Accessing State outside View.body. To avoid it, you should either remove the @State. Which makes sense because includeDecimal is not a source of truth. Its value is derived from amount. By removing @State, however, includeDecimal will not update if amount changes. To achieve that, the best option, is to define your includeDecimal as a computed property, so that its value is derived from the source of truth (amount). This way, whenever the amount changes, your includeDecimal does too. If your view depends on includeDecimal, it should update when it changes:

    struct AmountView : View {
        @Binding var amount: Double
        
        private var includeDecimal: Bool {
            return round(amount)-amount > 0
        }
        
        init(withAmount: Binding<Double>) {
            self.$amount = withAmount
        }
        var body: some View { ... }
    }
    

    As indicated by rob mayoff, you can also use $$varName (beta 3), or _varName (beta4) to initialise a State variable:

    // Beta 3:
    $$includeDecimal = State(initialValue: (round(amount.value) - amount.value) != 0)
    // Beta 4:
    _includeDecimal = State(initialValue: (round(amount.value) - amount.value) != 0)
    

    From Stack Overflow: asked by keegan3d, answered by kontiki (CC BY-SA 4.0)

  8. How can I round specific corners of a View?

    Demo (Source code is available at the end of the post)

    iOS 16+ built-in modifier (Xcode 15 needed)

    Clip the view using the new UnevenRoundedRectangle:

    .clipShape(
        .rect(
            topLeadingRadius: 0,
            bottomLeadingRadius: 20,
            bottomTrailingRadius: 0,
            topTrailingRadius: 20
        )
    )
    

    Note: Although it works from iOS 16, .rect needs Xcode 15 to be available.

    iOS 13+

    You can use it like a normal modifier:

    .cornerRadius(20, corners: [.topLeft, .bottomRight])
    

    You need to implement a simple extension on View like this:

    extension View {
        func cornerRadius(_ radius: CGFloat, corners: UIRectCorner) -> some View {
            clipShape( RoundedCorner(radius: radius, corners: corners) )
        }
    }
    

    And here is the struct behind this:

    struct RoundedCorner: Shape {
        let radius: CGFloat
        let corners: UIRectCorner
        init(radius: CGFloat = .infinity, corners: UIRectCorner = .allCorners) {
            self.radius = radius
            self.corners = corners
        }
        func path(in rect: CGRect) -> Path {
            let path = UIBezierPath(roundedRect: rect, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
            return Path(path.cgPath)
        }
    }
    

    You can also use the shape directly as a clipping mask.

    Sample Project:

    iOS 13 - Source code on gist

    iOS 16 - Source code on gist

    From Stack Overflow: asked by Richard Witherspoon, answered by Mojtaba Hosseini (CC BY-SA 4.0)

Related topics

Where these questions come from

Open-source collections on GitHub, official documentation, a government careers service and the Stack Exchange sites, each used under its own licence. The answers are the authors' own words: we only tidy the layout, leave out pictures, and cut a long answer with a link to the rest. Stack Exchange answers stay under CC BY-SA and name who asked and who answered.