6

SwiftUI Color Picker Tutorial

 3 years ago
source link: https://www.ioscreator.com/tutorials/swiftui-color-picker-tutorial
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
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")
        }
    }
}
  1. 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

  2. A rectangle is displayed with a fill color corresponding to the current selected color of the color picker.

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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK