Categories
Uncategorized

SwiftUI – How to create a Picker

Creating a Picker in SwiftUI is very simple – give it a try 🚀

A picker in SwiftUI is a piece of UI that includes one or multiple lists displayed as a wheel. The user can use this wheel(s) for selecting a specific value. Pickers are often found within iOS apps. Take a look at the date selection in the system’s Calendar app or the time selection in the Clock app 🕓⠀

Here is how to create a Picker in SwiftUI 👇

Step 1: Create a State property for keeping track of the current selection.⠀ ⠀

Step 2: Create the data set for your Picker, in our example it‘s an array holding color names as Strings.⠀ ⠀

Step 3: Create a Picker with binding it to the State and providing it with a suitable Label. If you want no label, just insert a Text with an empty String⠀ ⠀

Step 4: Inside the Picker, implement a ForEach loop that cycles through every object of your data set. You can then use the loop‘s closure for creating one Text object for every object of the data set and assigning with an index.⠀ ⠀ SwiftUI then knows which index every object should have and updates the State depending on the current selection! You can then use the State‘s value, for example as we do with a Text displaying the selected color.

struct ContentView: View {
    //1. Create a State for keeping track of the current selection
    @State var selection = 0
    //2. Create an array for holding the picker's content
    let colors = ["Green", "Blue", "Orange", "Yellow"]

    var body: some View {
        VStack {
            //3. Create the Picker by binding it to the State and providing it with a label
            Picker(selection: $selection, label: Text("MyPicker")) {
                //4. Create on row for every String in your array and assign it to a index
                ForEach(0 ..< colors.count) { index in
                     Text(self.colors[index]).tag(index)
                }
            }
            Text("Selected color: \(colors[selection])")
                .padding(.bottom, 70)
        }
    }
}


If you want to learn more about SwiftUI, make sure you check out our free SwiftUI Basics eBook and our other tutorials! Also make sure you follow us on Instagram and subscribe to our newsletter to not miss any updates, tutorials and tips about SwiftUI and more!

Categories
Uncategorized

SwiftUI – How to create a Navigation Bar with custom items

Updated for Xcode 12.0 and SwiftUI 2.0 ✅

Customizing the navigation bar in SwiftUI by inserting bar items is super easy using the .toolbar modifier. Here’s how to do it! 👇

Step 1: Make sure your whole view is wrapped into a NavigationView. This injects you view into a navigation hierarchy allowing to user to navigate by pushing and popping views embedded into this hierarchy.

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

Step 2: Add a navigation bar title to your navigation view. We do this using the .navigationTitle modifier. By using the “displayMode” argument, you can also decide if you want a large or a normal sized navigation bar.

var body: some View {
        NavigationView {
            Text("Hello, World!")
                .navigationTitle("Photo Editor")
        }
    }

Step 3: Now, we’re ready to add items to our navigation bar. Until recently, we would have done this using the .navigationBarItems modifier. But since this modifier is deprecated in Xcode 12, we need to use the new .toolbar modifier.

NavigationView {
            Text("Hello, World!")
                .navigationTitle("Photo Editor")
                .toolbar(content: {

                })
        }

The new .toolbar modifier is a result of SwiftUI 2.0 following a more cross-platform oriented development approach. 

Fortunately, the .toolbar modifier is quite easy to understand. To add navigation bar items, we just need to inject ToolbarItem instances into the .toolbar closure.

Step 4: Inside the .toolbar closure, add one ToolbarItem for each tab bar item. Use the “placement” argument to set the position of the item. Finally, you can wrap Button containing an Image view inside each ToolbarItem. 

.toolbar(content: {
                    ToolbarItem(placement: .navigationBarLeading) {
                        Button(action: {
                                addTask()
                        }) {
                            Image(systemName: "plus.circle")
                                .imageScale(.large)
                        }
                    }
                    ToolbarItem(placement: .navigationBarTrailing) {
                        Button(action: {
                                removeTask()
                        }) {
                            Image(systemName: "minus.circle")
                                .imageScale(.large)
                        }
                    }
                })

That’s it! 

Complete example:

And that’s it! Now you’re able to create your own Navigation Bar with custom items in SwiftUI.

struct ContentView: View {
    
    @State var items = [Item]()
    
    var body: some View {
        //Step 1: Wrap your ContentView into a NavigationView
        NavigationView {
            List(items) { item in
                Text(item.name)
            }
                //Step 2: Add a navigation bar title
                .navigationTitle("Photo Editor")
                //Step 3: Initialize a toolbar
                .toolbar(content: {
                    //Step 4: Declare one ToolBarItem for each navigation bar button and set the position
                    ToolbarItem(placement: .navigationBarLeading) {
                        Button(action: {
                                addTask()
                        }) {
                            Image(systemName: "plus.circle")
                                .imageScale(.large)
                        }
                    }
                    ToolbarItem(placement: .navigationBarTrailing) {
                        Button(action: {
                                removeTask()
                        }) {
                            Image(systemName: "minus.circle")
                                .imageScale(.large)
                        }
                    }
                })
        }
    }
    
    func addTask() {
        let item = Item(id: items.count+1, name: "Sample Task")
        items.append(item)
    }
    
    func removeTask() {
        items.removeLast()
    }
}


I hope you enjoyed this tutorial! If you want to learn more about SwiftUI, make sure you check out our free SwiftUI Basics eBook and our other tutorials! Also make sure you follow us on Instagram and subscribe to our newsletter to not miss any updates, tutorials and tips about SwiftUI and more!

Categories
Uncategorized

How to create a custom SwiftUI Slider

You want to create a custom SwiftUI Slider in SwiftUI? Here you go! 👇

Step 1: Add a State property to your view’s body for keeping track of the currently selected value. It should be a Float.

Step 2: Create a HStack for aligning the Slider and it’s icons horizontally.

Step 3: Initialise and modify the items. Here you can use system- or custom icons and selected a color for them.

Step 4: Insert a Slider object by initialising it with binding it to the declared State and providing it with a floating range of values that can be selected. You can modify the Slider’s color by using the .accentColor modifier.


struct ContentView: View {

    //1. Add a State for keeping track of the current selection
    @State var currentValue = 4.0

    var body: some View {
        VStack {
            //2. Create a HStack for alining the Slider and it's icons horizontally
            HStack {
                //3. Initialise and modify the items
                Image(systemName: "sun.min")
                    .resizable()
                    .frame(width: 30, height: 30)
                    .foregroundColor(.orange)
               //4. Initalise the Slider by binding it to the State and providing it with a range of values
                Slider(value: $currentValue, in: 0.0...10.0)
                    //5. Modify the Slider's color
                    .accentColor(.orange)
                    .padding()
                Image(systemName: "sun.max")
                    .resizable()
                    .frame(width: 30, height: 30)
                    .foregroundColor(.orange)
            }
                .padding()
            Text("Current value: \(Int(currentValue))")
        }
    }
}

You just learned how a custom SwiftUI Slider can be created!


I hope you enjoyed this tutorial! If you want to learn more about SwiftUI, make sure you check out our free SwiftUI Basics eBook and our other tutorials! Also make sure you follow us on Instagram and subscribe to our newsletter to not miss any updates, tutorials and tips about SwiftUI and more!

Categories
Uncategorized

SwiftUI – How to frame an Image

Wanna know how to frame an Image properly in SwiftUI? Here you go! 👇

Step 1: Apply to .resizable modifier to your Image object. This modifier enables to resize and frame the image properly

Step 2: When changing the size of your Image you normally want to keep the original dimensions. For this purpose, add the .aspectRatio modifier. You can choose between the .fill content mode which ensures that the whole frame gets filled out with the Image and the .fit content mode which instead ensures that the whole Image fits within the frame.

Step 3: Now you can declare the frame for the Image


Step4: Add the .clipped modifier for making sure that any parts of your Image exceeding the frame get cut off.

import SwiftUI
    struct ContentView : View {
    var body: some View {
        Image("dog")
            //Enable size editing for the Image
            .resizable()
            //Define which method to use to keep the original dimensions when resizing
            .aspectRatio(contentMode: .fill)
            //Declare the frame for your image
            .frame(width: 380, height: 280)
            //Cut out the exceeding parts of the image
            .clipped()
    }
}

And this is how you frame an Image in SwiftUI!


I hope you enjoyed this tutorial! If you want to learn more about SwiftUI, make sure you check out our free SwiftUI Basics eBook and our other tutorials! Also make sure you follow us on Instagram and subscribe to our newsletter to not miss any updates, tutorials and tips about SwiftUI and more!

Categories
Uncategorized

SwiftUI – How to create and style a Text Field

Wanna know how to create and customize a Text Field in SwiftUI? Here you go! 👇

Step 1: Create a State property that holds the user’s input. For more on how State properties work and how they are used with Text fields check out our login page tutorial!

Step 2: Initialize the TextField object. Enter a string which serves as the placeholder when the TextField is empty. Next, you need to bind the created State propery to the TextField to enable data flow between them. To understand the data flow concept in SwiftUI we recommend you our login page tutorial as well.

Step 3: In SwiftUI, we style the Text Field by adding modifiers to it. For example you can add a rounded background and paddings to the TextField

import SwiftUI

let lightGreyColor = Color(red: 239.0/255.0, green: 243.0/255.0, blue: 244.0/255.0, opacity: 1.0)

struct ContentView : View {
    //Create a State property that holds the user's input
    @State var userInput = ""

    var body: some View {
        //Initialize the Text Field, provide it with a placeholder title and bind it to the State
        TextField("Enter something...", text: $userInput)
            //Style your Text Field
            .padding()
            .background(lightGreyColor)
            .cornerRadius(5.0)
            .padding()
    }
}

And that’s everything you need to know to use a Text Field for your SwiftUI app.


I hope you enjoyed this tutorial! If you want to learn more about SwiftUI, make sure you check out our free SwiftUI Basics eBook and our other tutorials! Also make sure you follow us on Instagram and subscribe to our newsletter to not miss any updates, tutorials and tips about SwiftUI and more!