Text
SwiftUI Stack View Tutorial
Stack Views in SwiftUI can be used to compose layouts.. In this tutorial a vertical stack(VStack) and a horizontal stack(HStack) will be displayed. This tutorial is built for iOS15 and Xcode 13, which can be download at the Apple developer portal.
Open Xcode and either click Create a new Xcode project in Xcode’s startup window, or choose File > New > Project. In the template selector, select iOS as the platform, In the Application section select the App template, and then click Next.
Enter SwiftUIStackViewTutorial as the Product Name, select the Use SwiftUI checkbox, and click Next. Choose a location to save the project on your Mac.
In the canvas, click Resume to display the preview. If the canvas isn’t visible, in the Editor menu select Canvas to show it.
In the Project navigator, click to select ContentView.swift. The body property needs to return one view, so the following code won’t compile, since there are two text views.
struct ContentView: View { var body: some View { Text("Hello") Text("SwiftUI!") } }
Multiple views can be combined and embedded in stack views, which group views together. Command-click the text view to show the structured editing popover, and then choose Embed in VStack.
This will embed the text views into a VStack. Also set the font of all items in the Vstack to .largeTitle using the font modifier. Putting a spacer below the text views will push them to the top. Default padding and a thick border line will surround the VStack.
struct ContentView: View { var body: some View { VStack { Text("Hello") Text("SwiftUI!") Spacer() } .font(.largeTitle) .padding() .border(Color.red, width: 5) } }
The preview shows the two text views vertically stacked.
The elements inside a stack can also be customized by adding spacing, which will enlarge the vertical distance between the elements.
struct ContentView: View { var body: some View { VStack(spacing: 50){ Text("Hello") Text("SwiftUI!") Spacer() } .font(.largeTitle) .padding() .border(Color.red, width: 5) } }
By default, items in your stacks are aligned centrally. To align both text views horizontal to the leading edge edge of the Stack change the code to
struct ContentView: View { var body: some View { VStack(alignment: .leading, spacing: 50) { Text("Hello") Text("SwiftUI!") Spacer() } .font(.largeTitle) .padding() .border(Color.red, width: 5) } }
Remove the VStack code block and add a horizontal stack to the content view.
struct ContentView: View { var body: some View { VStack { HStack(spacing: 10) { Text("Mac") Text("iPad") Text("iPhone") Text("Watch") } .font(.largeTitle) .padding() .border(Color.red, width: 5) Spacer() } } }
The text views inside the horizontal stack are positioned horizontally. The HStack is initialized with a spacing of 10. The Stack is nested inside a Stack which includes a Spacer to push the Stack to the top of the screen..
The source code of the SwiftUIStackViewTutorial can be downloaded at the ioscreator repository on Github.
0 notes
Text
SwiftUI Getting Started Tutorial
At WWDC19 Apple introduces SwiftUI, which is a native declarative UI framework. SwiftUI let developers declare what they want to put in the UI and SwiftUI makes sure all rules are enforced. SwiftUI is also cross-platform that works across iOS, macOS, tvOS and watchOS. In this tutorial a basic SwiftUI project will be created to show the fundamentals of SwiftUI. This tutorial is built for iOS15 and Xcode 13, which can be download at the Apple developer portal.
Open Xcode and either click Create a new Xcode project in Xcode’s startup window, or choose File > New > Project. In the template selector, select iOS as the platform, select the App template, and then click Next.
Enter SwiftUIGettingStartedTutorial as the Product Name, select the Use SwiftUI checkbox, and click Next. Choose a location to save the project on your Mac.
The basic Single View App template includes the <ProjectName>App file,in this project the SwiftUIGettingStartedTutorialApp.swift file which is the entry point of the App..
@main struct SwiftUIGettingStartedTutorialApp: App { var body: some Scene { WindowGroup { ContentView() } } }
The ContentView is placed inside a window group to make it visible. In the Project navigator, click to select ContentView.swift. The ContentView structure describes the view’s content and layout.
struct ContentView: View { var body: some View { Text("Hello World") } }
The ContentView_Preview struct declares a preview for that view.
struct ContentView_Preview: PreviewProvider { static var previews: some View { ContentView() } }
In the canvas, click Resume to display the preview. If the canvas isn’t visible, select Editor > Editor and Canvas to show it.
The preview will display the Hello World text, now change the text view in the Editor.
Text("Hello ioscreator")
As the code is changed, the preview updates to reflect the changes.
It is also possible to change the code by using the inspector. Command-click the Text in the preview and choose Inspect.
Change the Font modifier to Large Title. This applies the large title text style to the Text View.
The code view is updated with the font modifier and the preview window will update the appearance of the text view.
Text("Hello ioscreator") .font(.largeTitle)
Modifiers can be used to customize a SwiftUI view. In the Edtor Add the .foregroundColor(.red) modifier.
struct ContentView : View { var body: some View { Text("Hello ioscreator") .font(.largeTitle) .foregroundColor(.red) } }
This changes the text's color to red in the preview.
The source code of the SwiftUIGettingStartedTutorial can be downloaded at the ioscreator repository on Github.
0 notes
Text
SwiftUI Preview Orientation Tutorial
in SwiftUI the preview can be displayed with different orientation using the previewInterfaceOrientation() modfier.. In this tutorial the preview will be displayed with the four different oriientations. portrait, portraitUpsideDown, landscapeLeft and landscapeRight. This tutorial is built for iOS15 and Xcode 13, which can be download at the Apple developer portal.
Open Xcode and either click Create a new Xcode project in Xcode’s startup window, or choose File > New > Project. In the template selector, select iOS as the platform, select App template in the Application section and then click Next.
Enter SwiftUIPreviewOrientationTutorial as the Product Name, select SwiftUI as Interface, SwiftUI App as Life Cycle and Swift as Language. Deselect the Include Tests checkbox and click Next. Choose a location to save the project on your Mac.
In the canvas, click Resume to display the preview. If the canvas isn’t visible, select Editor > Editor and Canvas to show it.
In the Project navigator, click to select ContentView.swift. Change the ContentView_Previews struct to
struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() ContentView() .previewInterfaceOrientation(.landscapeLeft) ContentView() .previewInterfaceOrientation(.landscapeRight) ContentView() .previewInterfaceOrientation(.portraitUpsideDown) } }
The default preview interface orientation is portrait, so it isn’t required to specify it.
The preview for the landscapeleft orientation will look like this.
The preview for the landscaperight orientation will look like this.
The preview for the portraitupsidedown orientation will look like this.
The source code of the SwiftUIPreviewOrientationTutorial can be downloaded at the ioscreator repository on Github.
0 notes
Text
SwiftUI Custom Swipe Actions Tutorial
in SwiftUI a custom swipe action can be displayed when an row on a List is swiped. The action can be displayed left or right and can be displayed with a custom tint color and a system image.. In this tutorial some swipe actions can be triggered which will update the navigation title. This tutorial is built for iOS15 and Xcode 13, which can be download at the Apple developer portal.
Open Xcode and either click Create a new Xcode project in Xcode’s startup window, or choose File > New > Project. In the template selector, select iOS as the platform, select App template in the Application section and then click Next.
Enter SwiftUICustomSwipeActionsTutorial as the Product Name, select SwiftUI as Interface, SwiftUI App as Life Cycle and Swift as Language. Deselect the Include Tests checkbox and click Next. Choose a location to save the project on your Mac.
In the canvas, click Resume to display the preview. If the canvas isn’t visible, select Editor > Editor and Canvas to show it.
In the Project navigator, click to select ContentView.swift. Change the ContentView struct to
struct ContentView: View { // 1. @State private var action = "" var body: some View { NavigationView { List { ForEach(1..<6) { i in Text("Item \(i)") // 2. .swipeActions(edge: .leading, allowsFullSwipe: false) { Button { action = "Star" } label: { Label("Star", systemImage: "star.circle") } .tint(.yellow) } // 3. .swipeActions(edge: .trailing) { Button(role: .destructive){ action = "Trash" } label: { Label("Trash", systemImage: "trash.circle") } } // 4. .swipeActions(edge: .trailing) { Button{ action = "Flag" } label: { Label("Flag", systemImage: "flag.circle") } } } } // 5. .navigationTitle("\(action)") } } }
A propery array of action is declared and will be used for the navigation title
The swipeActions modifier contains a button with the star systemImage. The allowfullswipe parameter is used to auto select the action when a full swipe is inititated. Here this is disabled.
The swipeActions modifier contains a button with a trash systemImage. The destructive role display the action in a red color.
A blue button item is displayed containing the flag systemimage.
The navigationTitle is updated when the action is triggered.
Go to the Preview and select Live Preview. Swipe on a item from the List to initiate a custom action. The navigation Title will be updated with the corresponding Label title.
The source code of the SwiftUICustomSwipeActionsTutorial can be downloaded at the ioscreator repository on Github.
0 notes
Text
SwiftUI Search Bar Tutorial
in SwiftUI a Search Bar can be displayed inside a List using the searchable modifier. When using the Search Bar the results will be displayed automatically. In this tutorial a list of countries is displayed and can be searched.This tutorial is built for iOS15 and Xcode 13, which can be download at the Apple developer portal.
Open Xcode and either click Create a new Xcode project in Xcode’s startup window, or choose File > New > Project. In the template selector, select iOS as the platform, select App template in the Application section and then click Next.
Enter SwiftUISearchBarTutorial as the Product Name, select SwiftUI as Interface, SwiftUI App as Life Cycle and Swift as Language. Deselect the Include Tests checkbox and click Next. Choose a location to save the project on your Mac.
In the canvas, click Resume to display the preview. If the canvas isn’t visible, select Editor > Editor and Canvas to show it.
In the Project navigator, click to select ContentView.swift. Change the ContentView struct to
struct ContentView: View { // 1. let countries = ["Afghanistan", "Albania", "Algeria", "Angola", "Argentia", "Armenia", "Australia", "Austria"] // 2. @State private var searchString = "" var body: some View { NavigationView { List { // 3. ForEach(searchString == "" ? countries: countries.filter { $0.contains(searchString)}, id: \.self) { country in Text(country) } .navigationTitle("Countries") } // 4. .searchable(text: $searchString) } } }
A propery array of countries is declared.
The searchstring holds the text entered inside the search bar.
The regular countries will be displayed when the search bar is empty. When the user inserts the search string, the list is searched with that string and the results are displayed
The searchable modifier displays the Search Bar and hold the searchString binding
Go to the Preview and select Live Preview. The countries list is displayed.
Enter The text to be searched inside the Search Bar and the results will be displayed.
The source code of the SwiftUISearchBarTutorial can be downloaded at the ioscreator repository on Github.
0 notes
Text
SwiftUI Pull to Refresh Tutorial
The Pull to Refresh functionality can be used to refresh contents of a List by pulling down. SwiftUI introduced the refreshablel() modifier. In this tutorial a JSON file will be fetched from the internet and displayed in a list when the pull to refresh is initiated..This tutorial is built for iOS15 and Xcode 13, which can be download at the Apple developer portal.
Open Xcode and either click Create a new Xcode project in Xcode’s startup window, or choose File > New > Project. In the template selector, select iOS as the platform, select App template in the Application section and then click Next.
Enter SwiftUIPullToRefreshTutorial as the Product Name, select SwiftUI as Interface, SwiftUI App as Life Cycle and Swift as Language. Deselect the Include Tests checkbox and click Next. Choose a location to save the project on your Mac.
In the canvas, click Resume to display the preview. If the canvas isn’t visible, select Editor > Editor and Canvas to show it.
In the Project navigator, click to select ContentView.swift. Above the ContentView struct add a new Contact struct to hold the items of the json file which will be loaded.
struct Contact: Decodable, Identifiable { let id: Int let name: String let email: String }
Change the ContentView struct to
struct ContentView: View { // 1. @State private var contacts = [ Contact(id: 0, name: "SwiftUI", email: "Pull to refresh!")] var body: some View { NavigationView { // 2. List(contacts) { item in VStack(alignment: .leading) { Text(item.name) .font(.title) Text(item.email) .font(.subheadline) } } // 3. .refreshable { do { // 4. let url = URL(string: "https://ioscreator.com/s/contacts.json")! let (jsonData, _) = try await URLSession.shared.data(from: url) contacts = try JSONDecoder().decode([Contact].self, from: jsonData) } catch { // error contacts = [] } } } } }
A state propery array of contacts is declared which will hold the contacts. The first item is a stub item which will display the pull to refresh text in the List.
The List is displayed and contains the name and emall of the contact
The refreshable modifier is added to the List and will display an activity indicator while running the code.
The json file is fetched asynchronously and decoded into the Contacts struct.
Go to the Preview and select Live Preview.
Pull down the Pull to refresh item to load and display the contacts.
The source code of the SwiftUIPullToRefreshTutorial can be downloaded at the ioscreator repository on Github.
0 notes
Text
SwiftUI 3D Rotation Tutorial
The rotation3DEffect modifier rotates a view in 3D. The angle of the rotation can be set by the degrees parameter. In this tutorial a button will be rotated on the X-, Y- or Z-axis using Toggle Views. This tutorial is built for iOS14 and Xcode 12, which can be download at the Apple developer portal.
Open Xcode and either click Create a new Xcode project in Xcode’s startup window, or choose File > New > Project. In the template selector, select iOS as the platform, select App template in the Application section and then click Next.
Enter SwiftUI3DRotationTutorial as the Product Name, select SwiftUI as Interface, SwiftUI App as Life Cycle and Swift as Language. Deselect the Include Tests checkbox and click Next. Choose a location to save the project on your Mac.
In the canvas, click Resume to display the preview. If the canvas isn’t visible, select Editor > Editor and Canvas to show it.
In the Project navigator, click to select ContentView.swift. Change the code inside the ContentView struct to
struct ContentView: View { // 1. @State private var degrees = 0.0 // 2. @State private var rotateX = true @State private var rotateY = true @State private var rotateZ = true var body: some View { VStack(spacing: 30) { // 3. Toggle("Rotate X-axis", isOn: $rotateX) Toggle("Rotate Y-axis", isOn: $rotateY) Toggle("Rotate Z-axis", isOn: $rotateZ) // 4. Button("Hello World") { withAnimation(.easeIn(duration: 1)) { self.degrees += 360 } } .padding(20) .background(Color.red) .foregroundColor(Color.white) // 5. .rotation3DEffect(.degrees(degrees), axis: (x: rotateX ? 1 : 0, y: rotateY ? 1 : 0, z: rotateZ ? 1 : 0)) Spacer() } .padding() } }
a State properties is declared which holds the angle of the rotation
Three boolean state properties are declared which holds the state of the rotation of the corresponding axis.
The Toggles are displayed which can turn on and off the rotation of the axes.
The button will be animated with 360 degrees.
The rotation3DEffect modifier rotates the view in the axes which are turned on. in the toggles.
Go to the Preview and switch the toggles to select the axes. Press the “Hello Wordl” button to view the animation.
The source code of the SwiftUI3DRotationTutorial can be downloaded at the ioscreator repository on Github.
1 note
·
View note
Text
SwiftUI Background Color List Tutorial
The background color of items inside a List view can be changes using the .listRowBackground modifier. In this tutorial a list is displayed with alternate colors. This tutorial is built for iOS14 and Xcode 12, which can be download at the Apple developer portal.
Open Xcode and either click Create a new Xcode project in Xcode’s startup window, or choose File > New > Project. In the template selector, select iOS as the platform, select App template in the Application section and then click Next.
Enter SwiftUIListBackgroundColorTutorial as the Product Name, select SwiftUI as Interface, SwiftUI App as Life Cycle and Swift as Language. Deselect the Include Tests checkbos and click Next. Choose a location to save the project on your Mac.
In the canvas, click Resume to display the preview. If the canvas isn’t visible, select Editor > Editor and Canvas to show it.
In the Project navigator, click to select ContentView.swift. Change the code inside the ContentView struct to
struct ContentView: View { // 1. @State private var items = ["One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten"] var body: some View { List { // 2. ForEach(items.indices) { index in // 3. Text(items[index]) .listRowBackground((index % 2 == 0) ? Color(.systemBlue) : Color(.yellow)) } } } }
a State properties is declared which holds the array of numbers as strings.
A List is displayed containing the items of the array.
The .listRowBackground modifier set the background color for each item. the module operator is used to alternate the colors.
Go to the Preview to view the items with alternate background colors in the List.
The source code of the SwiftUIListBackgroundColorTutorial can be downloaded at the ioscreator repository on Github.
0 notes
Text
SwiftUI ScrollViewReader tutorial
In SwiftUI a ScrollViewReader is a view that provides programmatic scrolling inside sub views. With the scrollTo method the scrolling is executed. In his tutorial an item number can be chosen using a stepper. When the number is selected the ScrollViewReader will scroll to the chosen item. This tutorial is built for iOS 14 and Xcode 12, which can be download at the Apple developer portal.
Open Xcode and either click Create a new Xcode project in Xcode’s startup window, or choose File > New > Project. In the template selector, select iOS as the platform, select App template in the Application section and then click Next.
Enter SwiftUIScrollViewReaderTutorial as the Product Name, select SwiftUI as Interface, SwiftUI App as Life Cycle and Swift as Language. Deselect the Include Tests checkbos and click Next. Choose a location to save the project on your Mac.
In the canvas, click Resume to display the preview. If the canvas isn’t visible, select Editor > Editor and Canvas to show it.
In the Project navigator, click to select ContentView.swift. Change the code inside the ContentView struct to
struct ContentView: View { // 1. let colors: [Color] = [.yellow, .red, .blue] @State private var itemNumber = 1 var body: some View { ScrollView { // 2. ScrollViewReader { value in HStack { // 3. Stepper(value: $itemNumber, label: { Text("Jump to Item: ") }) Button { withAnimation { // 4. value.scrollTo(itemNumber) } } label: { Text("\(itemNumber)") } }.padding() // 5. ForEach(1..<10) { i in Text("Item \(i)") .frame(width: 300, height: 200) .background(colors[i % colors.count]) .id(i) } } } } }
The property constant colors is use as background of the displayed items. The state variable will hold the current item number where will be scrolled to
The ScrollviewReader is used to provide access to the scrollTo method and the subview where will be scrolled to.
A stepper is displayed with the current value of the itemNumber which can be in- and decremented
The scrollTo(_:) method scrolls to the current view which matches the id of the view in the ForEach loop
The ForEach loop generates ten items with colored boxes, each item is assigned an id.
Go to the Preview and choose live preview. Change the number inside the stepper and click the number to scoll the selected colored item.
The source code of the SwiftUIScrollViewReaderTutorial can be downloaded at the ioscreator repository on Github.
0 notes
Text
SwiftUI Rotation Anchor Point Tutorial
In SwiftUI the rotationEffect method will rotate the view around a specific point which is called the anchor point. By default the anchor point is set to the the center point, but can be modified. In this tutorial some rectangles will be rotated at a different anchor point. This tutorial is built for iOS14 and Xcode 12, which can be download at the Apple developer portal.
Open Xcode and either click Create a new Xcode project in Xcode’s startup window, or choose File > New > Project. In the template selector, select iOS as the platform, select App template in the Application section and then click Next.
Enter SwiftUIRotationAnchorPointTutorial as the Product Name, select SwiftUI as Interface, SwiftUI App as Life Cycle and Swift as Language. Deselect the Include Tests checkbos and click Next. Choose a location to save the project on your Mac.
In the canvas, click Resume to display the preview. If the canvas isn’t visible, select Editor > Editor and Canvas to show it.
In the Project navigator, click to select ContentView.swift. Add a custom view modifier struct which will be used to set the modifiers for the rounded rectangles in the content view.
struct CustomRectangle: ViewModifier { var overlayText = "example" func body(content: Content) -> some View { return content .overlay(Text(overlayText).foregroundColor(.white)) .frame(width: 75, height: 75) .foregroundColor(Color.red) } }
The overlay text property can be changed as parameter of the .modifier modifier. Change the code inside the ContentView struct to
struct ContentView: View { // 1. @State private var isAnimated = false var body: some View { VStack(spacing: 15) { // 2. Button("Change") { self.isAnimated.toggle() } HStack(spacing: 10) { RoundedRectangle(cornerRadius: 10) // 3. .modifier(CustomRectangle(overlayText: "top left")) // 4. .rotationEffect(Angle.degrees(isAnimated ? 90: 0), anchor: .topLeading) .animation(.easeIn(duration: 0.5)) RoundedRectangle(cornerRadius: 10) .modifier(CustomRectangle(overlayText: "top right")) .rotationEffect(Angle.degrees(isAnimated ? -90: 0), anchor: .topTrailing) .animation(.easeIn(duration: 0.5)) } HStack(spacing: 10){ RoundedRectangle(cornerRadius: 10) .modifier(CustomRectangle(overlayText: "bottom left")) .rotationEffect(Angle.degrees(isAnimated ? 90: 0), anchor: .bottomLeading) .animation(.easeIn(duration: 0.5)) RoundedRectangle(cornerRadius: 10) .modifier(CustomRectangle(overlayText: "bottom right")) .rotationEffect(Angle.degrees(isAnimated ? -90: 0), anchor: .bottomTrailing) .animation(.easeIn(duration: 0.5)) } Spacer() } } }
The State property is declared to set the state of the animation.
The button will change the state of the isAnimated property
The custom modifier is used with a custom text as overlay text.
The top leading anchor point is used to rotate the rectangle.
The rotationEffect modifier will rotate the rectangles by changing the degrees of the Angle according to the state of the isAnimated property. The anchor parameter is set to the point at which the rectangle rotates. Go to the Preview and select the Live Preview button.
Click the Change button to see the rotation at different anchor point in action.
The source code of the SwiftUIRotationAnchorPointTutorial can be downloaded at the ioscreator repository on Github.
1 note
·
View note
Text
SwiftUI Popover Tutorial
In SwiftUI Popover can be attached to a view to display some content. On a iPhone the popover is presented as a Sheet and on an iPad it is presentd like a ContextMenu. In this tutorial a button is displayed which will present a popover when clicked. This tutorial is built for iOS14 and Xcode 12, which can be download at the Apple developer portal.
Open Xcode and either click Create a new Xcode project in Xcode’s startup window, or choose File > New > Project. In the template selector, select iOS as the platform, select App template in the Application section and then click Next.
Enter SwiftUIPopoverTutorial as the Product Name, select SwiftUI as Interface, SwiftUI App as Life Cycle and Swift as Language. Deselect the Include Tests checkbos and click Next. Choose a location to save the project on your Mac.
In the canvas, click Resume to display the preview. If the canvas isn’t visible, select Editor > Editor and Canvas to show it.
In the Project navigator, click to select ContentView.swift. Change the code inside the ContentView struct to
struct ContentView: View { // 1. @State var isPopoverPresented = false var body: some View { // 2. Button(action: { self.isPopoverPresented = true }) { Text("Show Popover") } // 3. .popover(isPresented: $isPopoverPresented) { Text("Popover is Presented") .font(.largeTitle) .frame(width: 500, height: 500) } } }
The isPopoverPresented State property is a boolean which determines if the popover is presented.
When the button is tapped, the isPopoverPresented property is set to true.
The popover is displayed with a text with the largeTitle font size.
Go to the Preview and click the Live Preview button. Click the Show Popover button to display the popover.
On an iPad the Popover does not cover the entire screen and an arrow is displayed. Change the ContentView_Previews struct to
struct ContentView_Previews: PreviewProvider { static var previews: some View { Group { ContentView() .previewDevice("iPhone 11") .previewDisplayName("iPhone 11") ContentView() .previewDevice("iPad (8th generation)") .previewDisplayName("iPad") } } }
This will add a iPad preview to the Preview pane. Click the Live Preview and click the display Popover button to present the popver on the iPad.
The source code of the SwiftUIPopverTutorial can be downloaded at the ioscreator repository on Github.
0 notes
Text
SwiftUI Map Type Tutorial
The MapType can be used to show the map as a standard type, but also as a satellite or hybrid type. Unfortunately the MapType property is not availlable in the MapView in SwiftUi at this time. Therefore the MapType from the MapKit framework in UIKit can be used. In this tutorial a region of New York is displayed with a segmented control to change the map type. This tutorial is built for iOS14 and Xcode 12, which can be download at the Apple developer portal.
Open Xcode and either click Create a new Xcode project in Xcode’s startup window, or choose File > New > Project. In the template selector, select iOS as the platform, select App template in the Application section and then click Next.
Enter SwiftUIMapTypeTutorial as the Product Name, select SwiftUI as Interface, SwiftUI App as Life Cycle and Swift as Language. Deselect the Include Tests checkbos and click Next. Choose a location to save the project on your Mac.
In the canvas, click Resume to display the preview. If the canvas isn’t visible, select Editor > Editor and Canvas to show it.
In the Project navigator, click to select ContentView.swift. Add the MapViewUIKit struct
import SwiftUI import MapKit struct MapViewUIKit: UIViewRepresentable { // 1. let region: MKCoordinateRegion let mapType : MKMapType // 2. func makeUIView(context: Context) -> MKMapView { let mapView = MKMapView() mapView.setRegion(region, animated: false) mapView.mapType = mapType return mapView } // 3. func updateUIView(_ mapView: MKMapView, context: Context) { mapView.mapType = mapType } }
These properties will be used when the Map View is displayed inside the ContentView
The makeUiView method creates a MKMapView object with the defined region and mapType
When the mapType is changed in the Content View, the Map is updated with the new mapType.
Change the code inside the ContentView struct to
struct ContentView: View { // 1 @State private var region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 40.61900, longitude: -74.14053) , span: MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05)) // 2 @State private var mapType: MKMapType = .standard var body: some View { ZStack { // 3 MapViewUIKit(region: region, mapType: mapType) .edgesIgnoringSafeArea(.all) VStack { Spacer() // 4 Picker("", selection: $mapType) { Text("Standard").tag(MKMapType.standard) Text("Satellite").tag(MKMapType.satellite) Text("Hybrid").tag(MKMapType.hybrid) } .pickerStyle(SegmentedPickerStyle()) .offset(y: -40) .font(.largeTitle) } } } }
The region State property is declared with the region of a part of the city New York
The mapType State propery is declared with the standard view type.
The MapViewUiKit object is called with the New York region and standard maptype
A Picker with type SegmentPickerStyle containing the different map types is displayed. When a segment is selected the mapType property value updates which will redraw the map with thus new type.
Go to the Preview and select Live View. Change the segments in the Picker to update the map type.
The source code of the SwiftUIMapTypeTutorial can be downloaded at the ioscreator repository on Github.
0 notes
Text
SwiftUI ScaleEffect Tutorial
In SwiftUI the ScaleEffect modifier can be used to shrink or enlarge the containing view . The content of the view will be altered not the frame size. In this tutorial a text view is displayed for which the scale effect can be changed using sliders and toggles to change the scale value. This tutorial is built for iOS14 and Xcode 12, which can be download at the Apple developer portal.
Open Xcode and either click Create a new Xcode project in Xcode’s startup window, or choose File > New > Project. In the template selector, select iOS as the platform, select App template in the Application section and then click Next.
Enter SwiftUIScaleEffectTutorial as the Product Name, select SwiftUI as Interface, SwiftUI App as Life Cycle and Swift as Language. Deselect the Include Tests checkbos and click Next. Choose a location to save the project on your Mac.
In the canvas, click Resume to display the preview. If the canvas isn’t visible, select Editor > Editor and Canvas to show it.
In the Project navigator, click to select ContentView.swift. Change the code inside the ContentView struct to
struct ContentView: View { // 1. @State private var xScaleEffect = 1.0 @State private var yScaleEffect = 1.0 @State private var isFlippedVertically = false @State private var isFlippedHorizontally = false var body: some View { VStack(spacing: 40) { Text("ScaleEffect") .font(.title) // 2. .scaleEffect(x: isFlippedVertically ? -1: 1) .scaleEffect(y: isFlippedHorizontally ? -1: 1) // 3. .scaleEffect(x: CGFloat(xScaleEffect)) .scaleEffect(y: CGFloat(yScaleEffect)) // 4. .border(Color.red, width: 2) // 5. Slider(value: $xScaleEffect, in: 0.0...5.0) Slider(value: $yScaleEffect, in: 0.0...5.0) // 6. Toggle(isOn: $isFlippedVertically) { Text("Flip Vertically") } Toggle(isOn: $isFlippedHorizontally) { Text("Flip Vertically") } Spacer() } .padding() } }
The State properties are declared which will hold the scale values and the flipped booleans in both directions.
The ScaleEffect modifier can be applied with negative values to flip the text View.
The scaleEffect contains a x and y value of type CGFloat which applies the scale. The default scale value is 1.0.
The border modifier is used to show the ScaleEffect modifier does not effect the frame size of the text view.
The sliders can be changed to change the x and y scale values
The toggles can be used to flip the text in both directions
Go to the Preview and select the Live Preview button. Change the sliders and toggles to change the scale effect on the text view.
The source code of the SwiftUIScaleeffectTutorial can be downloaded at the ioscreator repository on Github.
1 note
·
View note
Text
SwiftUI DisclosureGroup Tutorial
Disclosure Groups can show or hide a content view, which can be expanded or collapsed using a disclosure control. In this tutorial some examples of disclosre groups will be displayed. This tutorial is built for iOS14 and Xcode 12, which can be download at the Apple developer portal.
Open Xcode and either click Create a new Xcode project in Xcode’s startup window, or choose File > New > Project. In the template selector, select iOS as the platform, select App template in the Application section and then click Next.
Enter SwiftUIDisclosureGroupTutorial as the Product Name, select SwiftUI as Interface, SwiftUI App as Life Cycle and Swift as Language. Deselect the Include Tests checkbos and click Next. Choose a location to save the project on your Mac.
In the canvas, click Resume to display the preview. If the canvas isn’t visible, select Editor > Editor and Canvas to show it.
In the Project navigator, click to select ContentView.swift. Change the code inside the ContentView struct to
struct ContentView: View { // 1. @State private var settingsIsExpanded = true @State private var batteryIsExpanded = false @State private var soundIsExpanded = false @State private var isLowPowerModeOn = true @State private var volume: Double = 0 var body: some View { VStack { // 2. DisclosureGroup("Settings", isExpanded: $settingsIsExpanded) { // 3. DisclosureGroup("Battery", isExpanded: $batteryIsExpanded) { Toggle("Low Power Mode", isOn: $isLowPowerModeOn).padding() } .padding([.top, .leading, .trailing], 20.0) // 4. DisclosureGroup( isExpanded: $soundIsExpanded, content: { Slider(value: $volume, in: 0...100) }, label: { HStack(spacing: 20) { Image(systemName: "speaker") Text("Sound") } }) // 5. .accentColor(.red) .padding() } .padding() Spacer() } } }
Some State properties are declared which holds the collapsed or expanded state of the view with a boolean type
A disclosure group with the “Settings” label is displayed in the expanding state
Disclosure groups can be nested. Here the view is collapsed. When the disclosure control is selected, a toggle is displayed.
Here a different initializer of a disclosure group is used. This way the label can be customized using a system image for example.
The accentcolor modifier can be used to change the color of the disclosure control.
Go to the Preview to view the disclosure groups. Select the disclosure controls to change the state of the corresponding content views.
The source code of the SwiftUIDisclosureGroupTutorial can be downloaded at the ioscreator repository on Github.
0 notes
Text
SwiftUI Map Annotation Tutorial
In SwiftUI different annotation type can be displayed in a map view. Map pins, map markers and custom map annotations. In this tutorial some places of interest of the city of London will be displayed with the different annotation types. This tutorial is built for iOS14 and Xcode 12, which can be download at the Apple developer portal.
Open Xcode and either click Create a new Xcode project in Xcode’s startup window, or choose File > New > Project. In the template selector, select iOS as the platform, select App template in the Application section and then click Next.
Enter SwiftUIMapAnnotationtutorial as the Product Name, select SwiftUI as Interface, SwiftUI App as Life Cycle and Swift as Language. Deselect the Include Tests checkbos and click Next. Choose a location to save the project on your Mac.
In the canvas, click Resume to display the preview. If the canvas isn’t visible, select Editor > Editor and Canvas to show it.
In the Project navigator, click to select ContentView.swift. Import the MapKit framework at the top of the file
import MapKit
Insert the Place Struct which will hold the coordinate values of the different locations.
import MapKit struct Place: Identifiable { let id = UUID() let name: String let latitude: Double let longitude: Double var coordinate: CLLocationCoordinate2D { CLLocationCoordinate2D(latitude: latitude, longitude: longitude) } }
Change the ContentView struct to
struct ContentView: View { // 1. let places = [ Place(name: "British Museum", latitude: 51.519581, longitude: -0.127002), Place(name: "Tower of London", latitude: 51.508052, longitude: -0.076035), Place(name: "Big Ben", latitude: 51.500710, longitude: -0.124617) ] // 2. @State var region = MKCoordinateRegion( center: CLLocationCoordinate2D(latitude: 51.514134, longitude: -0.104236), span: MKCoordinateSpan(latitudeDelta: 0.075, longitudeDelta: 0.075)) var body: some View { // 3. Map(coordinateRegion: $region, annotationItems: places) { place in // Insert an annotation type here } .ignoresSafeArea(.all) } }
a places array is declared containing 3 places of interest in londen with the corresponding coordinates.
a region State property is declared containing a region of the city of london.
A Map view is displayed of the predefined region locations and size. The map contains the places with the annotation.
Unfortunately in the current version of SwiftUI only one type of annotation can be displayed inside a map view. First, insert the following line inside the Map view closure to display the MapPin annotation type.
MapPin(coordinate: place.coordinate)
The preview displays the map pin annotations.
Change the line to display the Mapmarker annotation type.
MapMarker(coordinate: place.coordinate)
The Preview now display the map marker annotations.
Change the line with the following code block to display the MapAnnotation type.
MapAnnotation(coordinate: place.coordinate, anchorPoint: CGPoint(x: 0.5, y: 0.5)) { Circle() .strokeBorder(Color.red, lineWidth: 10) .frame(width: 44, height: 44) }
The Preview displays each location with the annotation with a circle with a red outline color.
The source code of the SwiftUIMaoAnnotationTutorial can be downloaded at the ioscreator repository on Github.
0 notes
Text
SwiftUI Color Picker Tutorial
A Color Picker shows the currently selected color and allow users to select a new color.. In this tutorial a Rectangle is filled with the chosen color of the color picker. This tutorial is built for iOS14 and Xcode 12, which can be download at the Apple developer portal.
Open Xcode and either click Create a new Xcode project in Xcode’s startup window, or choose File > New > Project. In the template selector, select iOS as the platform, select App template in the Application section and then click Next.
Enter SwiftUIColorPickerTutorial as the Product Name, select SwiftUI as Interface, SwiftUI App as Life Cycle and Swift as Language. Deselect the Include Tests checkbos and click Next. Choose a location to save the project on your Mac.
In the canvas, click Resume to display the preview. If the canvas isn’t visible, select Editor > Editor and Canvas to show it.
In the Project navigator, click to select ContentView.swift. Change the code inside the ContentView struct to
struct ContentView: View { // 1. @State private var selectedColor = Color.red var body: some View { NavigationView { VStack(spacing: 20) { // 2. Rectangle() .fill(selectedColor) .frame(width: 100, height: 100) // 3. ColorPicker("Set the rectangle color", selection: $selectedColor) .padding() Spacer() }.navigationTitle("Color picker") } } }
A State property is declared which holds the selectedcolor oof the color picker. The default value is red, which will be used when the app starrs
A rectangle is displayed with a fill color corresponding to the current selected color of the color picker.
The color picker is displayed when the round colored icon is tapped.
Go to the Preview and press the Live Preview button. Select the round button to open the color picker.
Select a color using the prediefined colors or the sliders and close the color picker. The rectangle fill color is set with the selected color.
The source code of the SwiftUIColorPickerTutorial can be downloaded at the ioscreator repository on Github.
0 notes
Text
SwiftUI GroupBox Tutorial
In SwiftUI Group Boxes can be used to combine related views. It has a predefined styling of a background with rounded corners. The content is automatically placed inside a VStack. In this tutorial a Groupbox is displayed with a label field and one with custom styling. This tutorial is built for iOS14 and Xcode 12, which can be download at the Apple developer portal.
Open Xcode and either click Create a new Xcode project in Xcode’s startup window, or choose File > New > Project. In the template selector, select iOS as the platform, select App template in the Application section and then click Next.
Enter SwiftUIGroupBoxTutorial as the Product Name, select SwiftUI as Interface, SwiftUI App as Life Cycle and Swift as Language. Deselect the Include Tests checkbos and click Next. Choose a location to save the project on your Mac.
In the canvas, click Resume to display the preview. If the canvas isn’t visible, select Editor > Editor and Canvas to show it.
In the Project navigator, click to select ContentView.swift. Change the code inside the ContentView struct to
struct ContentView: View { @State private var name = "" var body: some View { VStack { // 1. GroupBox(label: Label("Heart rate", systemImage: "heart.fill").font(.largeTitle)) { Text("69 BPM").font(.title) } // 2. GroupBox { Text("Enter your name").font(.title) TextField("name", text: $name) } Spacer() }.padding(.horizontal) } }
The Groupbox has a text label built in, for which the default formatting can be overridden.
The Groupbox can also be used without the prebuilt label to create own custom styling.
Go to the Preview to view the two different GroupBox Views.
The source code of the SwiftUIGroupBoxTutorial can be downloaded at the ioscreator repository on Github.
0 notes