Categories
Uncategorized

How to limit the number of characters in a SwiftUI TextField

Did you ever ask yourself how to limit the number of characters that are allowed to enter into a SwiftUI TextField? To set the maximum length for a text field, follow these steps 👇


Step 1: First of all, create a new Swift file and make sure you import the SwiftUI framework (and the AudioToolbox framework for letting the device vibrate later on).

import SwiftUI
import AudioToolbox


Step 2: Inside this file, you need to create an @ObservableObject that serves as the TextField’s manager und updates the related ContentView whenever the TextField will get updated. 

import SwiftUI
import AudioToolbox

class TextFieldManager: ObservableObject {
  
    
}


Step 3: Within the the TextfieldManager, we create a constant for setting the maximum length for our TextField.

class TextFieldManager: ObservableObject {
    
    let characterLimit = 4
    
}


Step 4: Next, make sure to create a @Published property for holding the TextField’s input and for updating the related ContentView whenever the input changes.

class TextFieldManager: ObservableObject {
    
    let characterLimit = 4
    
    @Published var userInput = ""
    
}


Step 5: In your ContentView, create a TextFieldManager instance and observe it by using the @ObservedObject property wrapper.

struct ContentView: View {

    @ObservedObject var textFieldManager = TextFieldManager()

    var body: some View {
        //...
    }
}


Step 6: Now we can create our actual TextField and bind it to the @Published property of our TextFieldManager instance

var body: some View {
        TextField("Enter something...", text: $textFieldManager.userInput)
            .padding()
            .background(Color(red: 239.0/255.0, green: 243.0/255.0, blue: 244.0/255.0, opacity: 1.0))
            .cornerRadius(5.0)
            .padding()
    }


Step 7: Back to our TextFieldManager.swift file: We must react every time the TextField gets updated. We do this by using the didSet property observer. 

@Published var userInput = "" {
        didSet {
            
        }
    }


Step 8: So every time the user enters a character we want to check if the userInput already exceeds the character limit. If that’s the case, we crop the new value to the allowed number of characters.

@Published var userInput = "" {
        didSet {
            if userInput.count > characterLimit {
                userInput = String(userInput.prefix(characterLimit))
            }
        }
    }


Step 9: Optionally, you can let the device vibrate when the allowed number gets exceeded by using the following method.

didSet {
            if userInput.count > characterLimit {
                userInput = String(userInput.prefix(characterLimit))
                AudioServicesPlayAlertSoundWithCompletion(SystemSoundID(kSystemSoundID_Vibrate)) { return }
            }
        }


And that’s it. This is how you limit the number of characters in a SwiftUI TextField! ✨

I hope you enjoyed this tutorial! If you want to learn more about SwiftUI, check out 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 use auto-validating Text Fields in SwiftUI

Hello and welcome to a new SwiftUI tutorial! Today we’ll learn how to use an automatic validator for SwiftUI TextFields and SecureFields. By using auto-validating Text Fields, we can, for instance, automatically check if the user entered correct credentials without needing him to tap on a login button or something similar.

This is what we are going to create in this tutorial:

Setting up the Xcode project 🛠

To get started, create a new Xcode project. Make sure “Use SwiftUI” is selected. After creating the project, you can create some color sets in your Assets.xcassets folder for creating the neumorphic look as described in this tutorial.

Optionally, you can create some color sets for achieving the neumorphic look we’re going to use in this tutorial.

Next, click on File-New-File on your Xcode toolbar and create a new Swift file. Call this Constants. In this, we are going to store the correct pin the user needs to enter to get access to the home screen.

import Foundation

let pin = "1234"


That’s it! We’re ready to compose the UI of our app.

Composing the UI 🎨

We continue by composing the interface of our auto-validation app. For the look of this, we follow an approach called Neumorphism design. We made a whole tutorial about this design technique, so make sure you check it out.

First, we alter the background color of our ContentView. To do this, replace the default “Hello World” Text view with a ZStack and place a Rectangle inside it. Make sure the Rectangle is colored and covers the whole screen by using the following modifiers:

var body: some View {
        ZStack {
            Rectangle()
                .fill(Color("TextFieldColor"))
                .frame(maxWidth: .infinity, maxHeight: .infinity)
                .edgesIgnoringSafeArea(.all)
        }
    }


Note that we created the “TextFieldColor” in our Assets folder earlier, make sure you check it out this tutorial to see how you can do this.

On top of our background Rectangle, we put a VStack that contains the necessary Text views to instruct the user to enter his verification code.

ZStack {
            //...
            VStack(alignment: .leading) {
                Text("Please enter your verification code")
                    .font(.largeTitle)
                    .fontWeight(.semibold)
                    .padding(.top, 70)
                    .padding(.bottom, 20)
                Text("We have sent you a four-digit PIN to verificate your phone number.")
                    .lineLimit(2)
                    .fixedSize(horizontal: false, vertical: true)
                    .padding(.bottom, 20)
            }
        }


Now it’s time to create the Text Field. But before we can do this, we need to declare a @State property that hold’s the user’s input.

struct ContentView: View {
    
    @State var enteredPin = ""
    
    var body: some View {
        //...
    }
    
}


For hiding the user’s input we use a special type of a Text Field, a SecureField. We style this SecureField and set the numeric pad as the default keyboard type. Then, we push the VStack’s views up by using a Spacer.

VStack(alignment: .leading) {
                //...
                SecureField("PIN", text: $enteredPin)
                    .keyboardType(.numberPad)
                    .padding()
                    .background(Color("TextFieldColor"))
                    .cornerRadius(5.0)
                    .shadow(color: Color("LightShadow"), radius: 8, x: -8, y: -8)
                    .shadow(color: Color("DarkShadow"), radius: 8, x: 8, y: 8)
                Spacer()
            }


Finally, we apply some padding to the whole VStack:

VStack(alignment: .leading) {
                //...
            }
                .padding(30)


And that’s it! This is how your preview should look like now:

Creating the View Router 

Before moving on with implementing our Text Field auto-validating functionality, we need to think about what should happen when the user enters the right PIN. In this case, we want to present another view, for instance, the app’s home screen. Let’s create such a sample screen by clicking on File-New-File and creating a new SwiftUI view called HomeView. Inside the HomeView, we replace the “Hello World” Text with “Home”.

struct HomeView: View {
    var body: some View {
        Text("Home")
    }
}


But how can we navigate to this view when the user enters the right PIN?

Note: We made a tutorial about navigating independently in SwiftUI and we’re basically using the same technique as described in this, so make sure you check out.

First, we need to create our view router that manages which view should currently be presented to the user. For this purpose, create a new Swift file and call it ViewRouter. Make sure you import the SwiftUI framework. Inside this file, create a class also called ViewRouter and adopt the ObservableObject protocol so other views in our app can notice when something with the ViewRouter happens.

import Foundation
import SwiftUI


class ViewRouter: ObservableObject {
    
}


As said, our ViewRouter keeps track of which view should currently be shown. For this purpose, we create a @Published variable and call it currentPage. By default, we want to show our ContentView, which we will call “pin”. 

class ViewRouter: ObservableObject {
    
    @Published var currentPage = "pin"
    
}


Next, we need to set up our mother view that holds all views and shows either the ContentView or the HomeView. So let’s create a new SwiftUI view called MotherView. Inside this view, we observe the ViewRouter as an @EnvironmentObject, so every time the currentPage variable of the ViewRouter changes, we can show the corresponding view. We implement this functionality by writing:

struct MotherView: View {
    
    @EnvironmentObject var viewRouter: ViewRouter
    
    var body: some View {
        VStack {
            if viewRouter.currentPage == "home" {
                Text("Home")
            } else if viewRouter.currentPage == "pin" {
                ContentView()
            }
        }
    }
}


Next, we need to set our MotherView as the root view when the app launches. To do this, we go to our SceneDelegate.swift file and adjust the root view inside the scene function as follows:

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {

        let viewRouter = ViewRouter()
        
        if let windowScene = scene as? UIWindowScene {
            let window = UIWindow(windowScene: windowScene)
            window.rootViewController = UIHostingController(rootView: MotherView().environmentObject(viewRouter))
            self.window = window
            window.makeKeyAndVisible()
        }
    }


That’s it, now we’re capable of navigating to a new view which we will do when the user enters the correct PIN into the Text Field.

Again: If you didn’t understand what we just did with the ViewRouter, MotherView etc., please make sure you check out this tutorial where we explain everything in more detail.

Finally, we move the enteredPin @State of our ContentView into our ViewRouter class and turn it into a @Published property.

class ViewRouter: ObservableObject {
    
    @Published var enteredPin = ""
    
    //...
    
}

To bind our SecureField to the ViewRouter’s enteredPin property, we need to access it by using the @EnvironmentObject property wrapper inside our ContentView.

struct ContentView: View {
    
    @EnvironmentObject var viewRouter: ViewRouter
    
    var body: some View {
        //...
    }
    
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView().environmentObject(ViewRouter())
    }
}


Now, we can bind our SecureField to the viewRouter’s enteredPin property.

SecureField("PIN", text: $viewRouter.enteredPin)
                    //...

Validating the Text Field ☑️

Every time the user enters something into the Text Field, we want to compare it to the PIN we stored in our Constants.swift file earlier. To achieve such auto-validating Text Fields, we must react every time the enteredPin property, which is bound to the SecureField, gets updated. In Swift, we do this by using the didSet property observer. 

We can add this observer by placing curly braces followed by the didSet closure behind our viewRouter’s enteredPin property.

@Published var enteredPin = "" {
        didSet {
            
        }
    }

The code we write inside the didSet curly braces gets executed every time the user modifies the enteredPin property by entering a character into the SecureField.

So every time the user enters a character we want to check if the enteredPin equals the stored pin. When this happens, we change the currentPage variable to “home” which causes the observing MotherView to eventually show the user the HomeView.

@Published var enteredPin = "" {
        didSet {
            if self.enteredPin == pin {
                self.currentPage = "home"
            }
        }
    }

So let’s see if that works. Run your app (in the regular simulator!) and enter the correct pin. Awesome! Once you entered the complete pin, the enteredPin’s didSet property observer automatically notices and tells the viewRouter to grant the user access to the home screen. Great! You just learned how to create auto-validating Text Fields in SwiftUI.

Implementing Phone Vibration and limiting the entered TextField Characters 📳

However, we want to prevent the user from entering a value that is more than four digits long. Additionally, we want to erase the Text Field’s content once the user entered a four digit pin that is wrong and give him haptic feedback by letting the phone vibrate.

To do this, we add an else-if statement to our didSet property observer, which gets executed once the user entered a pin that is four or more digits long which is wrong.

@Published var enteredPin = "" {
        didSet {
            if self.enteredPin == pin {
                self.currentPage = "home"
            } else if enteredPin.count >= 4 {
                
            }
        }
    }

Inside this statement, we reset the enteredPin and let the phone vibrate by writing the following code:

enteredPin = ""
           AudioServicesPlayAlertSoundWithCompletion(SystemSoundID(kSystemSoundID_Vibrate)) { return }


Let’s try this out by running the app again and entering a wrong code. You see that the SecureField’s content automatically gets emptied again. Of course, the vibration only works if you run the app on a real device.

Conclusion 🎊

That’s it! With the described technique you can create auto-validating Text Fields that automatically react and, for instance, grants access to another view when the user enters the correct input.

We’ve uploaded the whole source code of this app to GitHub.

I hope you enjoyed this tutorial! If you want to learn more about SwiftUI, check out 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 show a SwiftUI onboarding screen only when to app launches for the first time

A lot of people recently asked us how to tell SwiftUI that a certain screen, for instance an onboarding view, should only be shown when the app launches the first time. To implement this functionality, follow the steps below👇



Step 1: Make sure you already set up your onboarding view that should be shown when the app launches for the first time. We made a whole tutorial about creating a multi-paged one.

struct OnboardingView: View {
    
    //Compose your Onboarding view, tutorial can be found here:
    //https://blckbirds.com/post/how-to-create-a-onboarding-screen-in-swiftui-1/
    
}

Step 2: Next, make sure you created your home view that should be shown when the app has already launched before.⠀

struct HomeView: View {
    //Compose your home view
}

Step 3: Next, we need to take control of when to show which view. For this purpose, we create an ObservableObject which serves as the “router” for our SwiftUI app’s views. This is basically the same technique we use for navigating independently between several views in SwiftUI.

class ViewRouter: ObservableObject {
    
    @Published var currentPage: String
    
}

Step 4: Next, we create the MotherView which holds both, our onboarding view and our default home view. Based on our ViewRouter’s currentPage property, we either load the onboarding or the home view.

struct MotherView : View {
    
    @EnvironmentObject var viewRouter: ViewRouter
    
    var body: some View {
        VStack {
            if viewRouter.currentPage == "onboardingView" {
                OnboardingView()
            } else if viewRouter.currentPage == "homeView" {
                HomeView()
            }
        }
    }
}

struct MotherView_Previews: PreviewProvider {
    static var previews: some View {
        MotherView().environmentObject(ViewRouter())
    }
}

Step 5: In our SceneDelegate.swift file’s scene function, we set our MotherView as the root view when the app launches.⠀

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {

        if let windowScene = scene as? UIWindowScene {
            let window = UIWindow(windowScene: windowScene)
            
            window.rootViewController = UIHostingController(rootView: MotherView().environmentObject(ViewRouter()))
            self.window = window
            window.makeKeyAndVisible()
        }
    }

Step 6: The trick now is to decide which view should be shown when the ViewRouter gets initialised (which is at the app’s launch!). For this purpose, we use UserDefaults. If there is already a key called “didLaunchBefore” stored, we tell our ViewRouter to show the home view at the app’s launch. When no key can be found, we know that it’s the first time the app launches and we tell our ViewRouter to display the onboarding view. Then, we create such a key so that when launching the app the next time, the home view gets chosen instead.⠀

class ViewRouter: ObservableObject {

    init() {
        if !UserDefaults.standard.bool(forKey: "didLaunchBefore") {
            UserDefaults.standard.set(true, forKey: "didLaunchBefore")
            currentPage = "onboardingView"
        } else {
            currentPage = "homeView"
        }
    }
    
    @Published var currentPage: String
    
}

And that’s it! With this technique, you can tell your SwiftUI app to show the onboarding screen only when the app launches for the first time 💡

We’ve uploaded the whole source code of this app to GitHub.

I hope you enjoyed this tutorial! If you want to learn more about SwiftUI, check out 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 multi-component picker

We already talked about how to create Pickers and date pickers in SwiftUI. However, it seems that in SwiftUI it’s currently not possible to create a custom picker with multiple components/sections. Well, here’s a little work-around!

Step 1: Create one State for every component of your picker for keeping track of which value of the particular section is currently selected.

struct ContentView: View {
    
    @State var day = 0
    @State var hourSelection = 0
    @State var minuteSelection = 0
    
    var body: some View {
        //...
    }
}


Step 2: Create the data sets for your sections. In our example we created 23 integers for the hours and 59 integers for the minutes.⠀

@State var day = 0
    @State var hourSelection = 0
    @State var minuteSelection = 0
    
    var days = [Int](0..<30)
    var hours = [Int](0..<24)
    var minutes = [Int](0..<60)
    
    var body: some View {
        //...
    }


Step 3: Create a Geometry Reader for knowing the overall view’s size. Especially, we need to know the view’s width since we want each component to of the picker to be equally wide. If you want to know more about how GeometryReaders in SwiftUI work, check out our Instagram post.⠀

var body: some View {
        GeometryReader { geometry in
            
        }
    }


Step 4: Inside a HStack, create one single picker for every component. In our example we created one picker for the days, one for the hours, and one for the minutes. ⠀

HStack {
                Picker(selection: self.$day, label: Text("")) {
                    ForEach(0 ..< self.days.count) { index in
                        Text("\(self.days[index]) d").tag(index)
                    }
                }
                Picker(selection: self.$hourSelection, label: Text("")) {
                    ForEach(0 ..< self.hours.count) { index in
                        Text("\(self.hours[index]) h").tag(index)
                    }
                }
                Picker(selection: self.$minuteSelection, label: Text("")) {
                    ForEach(0 ..< self.minutes.count) { index in
                        Text("\(self.minutes[index]) m").tag(index)
                    }
                }
            }


Step 5: Each picker component should be equally wide. So take the geometry size width and divide it by the number of components. Take this value for the width argument of the .frame modifier for every picker.⠀

HStack {
                Picker(selection: self.$day, label: Text("")) {
                    //...
                }
                    .frame(width: geometry.size.width/3, height: 100, alignment: .center)
                Picker(selection: self.$hourSelection, label: Text("")) {
                    //...
                }
                    .frame(width: geometry.size.width/3, height: 100, alignment: .center)
                Picker(selection: self.$minuteSelection, label: Text("")) {
                    //...
                }
                    .frame(width: geometry.size.width/3, height: 100, alignment: .center)
            }


This is how your preview should look like now:


That’s all! You can now use the selection states for subscripting the selected values out of your data sets. And that is how to create multi component Pickers in SwiftUI!

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

Neumorphism Design in SwiftUI

In this tutorial, we’ll talk about implement Neumorphism Interface Design into your SwiftUI app. You’ll get to know the biggest trend in user interface design in 2020 and how you can use it for your SwiftUI apps.

At the end of this tutorial, you’ll be able to create Neumorphism views like this in your SwiftUI app:

Example of a neumorphic design (dark appearance)

What is Neumorphism? 🔦

First of all, what is Neumorphism design? Neumorphism (also called Soft Design) is a combination of the current flat design approach and skeuomorphic principles. 

Skeuomorphic Design was really popular in the old days of mobile app development. Skeuomorphism basically means that visual elements are designed in such a way that they mimic their real-life counterparts.

Contrary to that, Flat Design follows a way more minimalistic approach. A realistic and three-dimensional representation of objects is avoided as far as possible.

The evolution of the iOS calculator app is a great example for comparing skeuomorphic design and flat design

Neumorphism (also called Soft Design) combines these two principles. Neumorphism follows a minimalistic approach as well, but while flat designed elements are “floating” on a perceived background by casting a simple shadow onto it, neomorphic elements seem to be “stamped out” from the background. This creates a smooth 3D-look which reminds us of the skeuomorphic days.

How can we achieve this Neumorphism effect in SwiftUI? First of all, the element itself needs to have the same color as its background. Note that neither the background nor the element should be purely white or black. Next, you need to cast a light shadow from the top left onto it. Finally, you cast a dark shadow from the bottom right onto it.

Creating the color sets 🎨

To implement the Neumorphism approach in SwiftUI, we recommend you to create the corresponding color sets first. To do this, go to your Xcode project’s Assets catalog and right-click to create a new color set.

You have to create three color sets in total. One for the background/element, one for the light shadow, and one for the dark shadow.

Make sure you create a dark mode alternative color every color set.

Make sure you also create an alternative color for the dark appearance of each color set

Here are suggestions of HEX colors you can use for your Neumorphism Design:

Light Mode Colors:

  • Background/Element: #DEEAF6
  • Light shadow: #F3F9FF
  • Dark shadow: #BECBD8

Dark Mode Colors:

  • Background/Element: #1A1B1E
  • Light shadow: #242529
  • Dark shadow: #151518

Tip: You can enter HEX values, by clicking on the specific color in your color set and clicking on “Show Color panel” in your attributes inspector.

When you’re finished with creating all three color sets, move on to creating the neomorphic SwitUI views.

Creating neumorphic SwiftUI views 💡

In your SwiftUI ContentView, start creating the colored background by creating a Rectangle that covers the whole screen like this:

struct Comparison: View {
    var body: some View {
        ZStack {
            Rectangle()
                .fill(Color("Background"))
                .frame(maxWidth: .infinity, maxHeight: .infinity)
                .edgesIgnoringSafeArea(.all)
        }
    }
}

Then, create your element and give it the same color as the background. In this example, we create a simple card by using a RoundedRectangle.

ZStack {
            Rectangle()
                .fill(Color("Background"))
                .frame(maxWidth: .infinity, maxHeight: .infinity)
                .edgesIgnoringSafeArea(.all)
            RoundedRectangle(cornerRadius: 20)
                .fill(Color("Background"))
                .frame(width: 300, height: 180)
        }

Finally, apply the light and the dark shadow by using the .shadow modifier with different colors and offset positions.

RoundedRectangle(cornerRadius: 20)
                .fill(Color("Background"))
                .frame(width: 300, height: 180)
                .shadow(color: Color("LightShadow"), radius: 8, x: -8, y: -8)
                .shadow(color: Color("DarkShadow"), radius: 8, x: 8, y: 8)


And that’s it! This is how your SwiftUI view should look now:

Conclusion 🎊

And that’s all! You can apply the technique used in this Tutorial to basically every element in your SwiftUI app to create that neumorphic look! ✨

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 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

Customizing the navigation bar in SwiftUI by inserting bar items is so easy, here’s how to do it! 👇

Step 1: Make sure your whole view is wrapped into a navigation view.

Step 2: Add a navigation bar title to your navigation view. With this modifier, you can also decide if you want a large or a default navigation bar (displayMode).

Step 3: Now you can add the navigationBarItems modifier! The leading parameter takes in all items that should get displayed on the “left side”, the trailing parameter the ones for the” right side”. If you want more than one item for each side, you can wrap the parameters input into an HStack. In this HStack you can now add a button which wraps an image (you bar item’s symbol!) You can also determine what should happen when the user taps on the bar item.


struct ContentView: View {

    @State var items = [Item]()

    var body: some View {
        //1. Embed your View into a Navigation View
        NavigationView {
            List(items) { item in
                Text(item.name)
            }
            //2. Add a Title for your Navigation Bar
            .navigationBarTitle(Text("To-Do"), displayMode: .inline)
            //.3 Add the Bar Items
            .navigationBarItems(trailing:
                HStack {
                    Button(action: {self.addTask()}) {
                    Image(systemName: "plus.circle")
                    }
                Button(action: {self.addTask()}) {
                    Image(systemName: "minus.circle")
                    }
                })
        }
    }

    func addTask() {
        let item = Item(id: items.count+1, name: "Sample Task")
        items.append(item)
    }

    func removeTask() {
        items.removeLast()
    }
}

struct Item: Identifiable {
    var id: Int
    var name: String
}

And that’s it! Now you’re able to create your own Navigation Bar with custom items 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 a Tab Bar

Creating a Tab Bar in SwiftUI is really simple – here’s how to do it 🚀

Tab Bar (known as UITabBars in UIKit) are perfect for providing the user the ability to quickly switch between different views.⠀ ⠀ Here is how to implement Tab Bars into your SwiftUI app 👇⠀

Step 1: Wrap your overall view, where you want to store your subviews in, into a TabView. This automatically creates a full functional Tab Bar for us!⠀ ⠀

Step 2: Insert the subviews into the Tab View wrapper. This automatically creates one “slot” for each subview inside your Tab Bar⠀ ⠀

Step 3: Create a Tab Bar item for every subview by adding the .tabItem modifier. You can choose any icon and label you want for each tab bar item 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 {
    var body: some View {
        //1. Create a TabView
        TabView {
            //2. Insert a subview into your TabView
            Text("Home View")
                //3. Create a tab bar item for each subview
                .tabItem {
                    Image(systemName: "house")
                    Text("Home")
                }
            Text("Settings View")
                .tabItem {
                    Image(systemName: "gear")
                    Text("Settings")
                }
        }
    }
}


Great, we just learned how to retrieve and parse JSON data from the web by using the Codeable protocol and our own data models. You are now able to work with API’s that provide data via JSON.

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!