Move to Page 09 – Page Control for iPhone App Development with UIKit in Swift

The page control is one of the best ways to effectively navigate between multiple pages or views in iPhone app development. Users can swipe each page with their fingers, and the page control indicates the current page’s status. In this course, we will take a closer look at how to implement a page control using Swift and UIKit.

1. Introduction to UIKit and Swift

UIKit is Apple’s main framework for iOS applications. Using UIKit makes it easier to build and manage user interfaces. Swift is one of the most commonly used programming languages for iOS application development. Swift is designed to be safe and fast, making it easier for developers to write code.

2. What is a Page Control?

A page control is a view that makes it easy to navigate between multiple pages. Users can select a specific page, and each page is usually displayed in a scrollable or carousel format. Page controls are typically displayed as circular dots, indicating which page is currently active.

2.1. Examples of Page Control Usage

  • Tutorial and guide pages
  • Image sliders
  • Onboarding processes

3. Basic Design

To implement a page control, you first need to design the UI. This process is primarily done through Interface Builder, but you can also create views programmatically. The next section will detail how to set up a page control in Xcode.

3.1. Creating a New Project in Xcode

1. Open Xcode and select 'Create a new Xcode project'.
2. Choose the 'App' template and then click 'Next'.
3. Enter a name for your project and select 'Swift' as the programming language.
4. Select 'Storyboard' for 'User Interface' and create the project.

3.2. Adding a Page Control in Storyboard

To add a page control to the storyboard, follow these steps:

1. Open the Main.storyboard file.
2. Search for 'Page Control' in the Object Library and drag it onto the View Controller.
3. Adjust thePosition of the page control to your desired location.
4. Set the number of pages to add (e.g., 3 pages) by adjusting the 'Number of Pages' property in the Attributes inspector.

4. Implementing the View Controller

Now it’s time to connect the page control and implement the UIViewController to display each page. Each page will be added to a UIScrollView, and the page control must be linked with the UIScrollView.

4.1. Setting Up the UIScrollView

1. Return to the View Controller in Main.storyboard and add a 'Scroll View'.
2. Set the Auto Layout constraints of the Scroll View to occupy the entire view.
3. Add multiple UIViews inside the Scroll View to arrange the content for each page.

4.2. Setting Up the ViewController.swift File

import UIKit

class ViewController: UIViewController, UIScrollViewDelegate {
    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var pageControl: UIPageControl!

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Set the ScrollView Delegate
        scrollView.delegate = self

        // Set the number of pages
        pageControl.numberOfPages = 3  // Adjust according to the number of pages
        pageControl.currentPage = 0

        // Set the Content Size
        scrollView.contentSize = CGSize(width: self.view.frame.size.width * 3, height: self.view.frame.size.height)
    }

    // Method called when the scroll view is scrolled
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let pageIndex = round(scrollView.contentOffset.x / self.view.frame.size.width)
        pageControl.currentPage = Int(pageIndex)
    }
}

5. Designing Page Content

Designing the content to add to each page is an important step. For example, you can add images, text, buttons, etc. The following explains how to add custom content for each page.

5.1. Designing Each Page UIView

1. Add a UIView inside the Scroll View in Main.storyboard.
2. Set the Auto Layout constraints of the UIView to span the entire Scroll View.
3. Add multiple UIViews to create pages (e.g., 3 pages).
4. Add UILabels, UIImageViews, etc., to each UIView to create content.

6. Adding Page Transition Animations

You can add animations to make transitions between pages appear smooth. Here, we will look at how to manually transition pages using UIButton.

6.1. Adding Buttons and Implementing Actions

1. Add the following code to the ViewController to implement functionality for transitioning to the previous and next pages.

@IBAction func nextPage(_ sender: UIButton) {
    let currentPage = pageControl.currentPage
    if currentPage < pageControl.numberOfPages - 1 {
        let nextPage = currentPage + 1
        let offset = CGSize(width: self.view.frame.size.width * CGFloat(nextPage), height: 0)
        scrollView.setContentOffset(offset, animated: true)
    }
}

@IBAction func previousPage(_ sender: UIButton) {
    let currentPage = pageControl.currentPage
    if currentPage > 0 {
        let previousPage = currentPage - 1
        let offset = CGSize(width: self.view.frame.size.width * CGFloat(previousPage), height: 0)
        scrollView.setContentOffset(offset, animated: true)
    }
}

7. Testing and Debugging

Once all implementations are complete, it is important to test the code on a real device or emulator. Check the transitions between pages, update states of the page control, and fix any bugs that may arise.

7.1. Debugging Tips

  • Use Xcode’s Debugger to track runtime errors.
  • Check if the UI elements are displayed correctly on the screen.
  • Use console logs to track state changes.

8. Conclusion

In this course, we learned how to implement a page control in an iPhone app using Swift and UIKit. The page control is an important UI element that makes it easy and intuitive for users to navigate between pages. We covered everything from basic implementation methods to page transition animations and UI design, so use this as a basis to apply to various apps.

Moving forward, aim to learn more about app development and enhance your skills through it. Additionally, effectively utilize code and UI components to create your own amazing apps!

Swift UIKit Style, iPhone App Development, 08 Displaying Maps with Map View

In this post, we will explore in detail how to develop an iPhone app using Swift in the UIKIT way and how to display a map using MapView. We will start with the basic concepts and gradually cover map view setup, location information handling, and various map-related feature implementations.

1. Understanding Swift and UIKIT

Swift is a programming language developed by Apple, used for iOS, macOS, watchOS, and tvOS app development. UIKIT is a framework used to construct the user interface (UI) of iOS. UIKIT provides various UI components to help developers easily build user interfaces.

2. Introduction to Map View

Map View provides the capability to integrate maps into apps based on Apple’s map services. Users can check their current location or search for specific places through the map. Additionally, it supports various features such as adding pins or displaying routes.

2.1. Basic Components of Map View

A map view consists of the following basic components:

  • Map Area: The area where users can view the map.
  • User Location: Represents the current location of the user.
  • Marker: A feature to pin specific locations, used to indicate places.
  • Route: A feature that visually represents the route between two points.

3. Setting Up the Xcode Project

Open Xcode and create a new project. Select ‘Single View App’ as the template. Choose the project name, language (Swift), and interface (UIKit), and then create the project.

3.1. Adding the MapKit Framework

To use the map, you need to add the MapKit framework. In the project navigator, select ‘ProjectName’ → ‘Targets’ → ‘General’, and then click the ‘+ button’ in the ‘Frameworks, Libraries, and Embedded Content’ section to add ‘MapKit’.

4. Implementing the Map View

Now, let’s implement the map view. First, open the ViewController in the storyboard and add the map view. Drag ‘Map View’ from the Object Library onto the ViewController.

4.1. Connecting IBOutlet

Connect the map view to code using IBOutlet. Hold down the Control key and drag the map view to the ViewController.swift file to create the IBOutlet.

import UIKit
import MapKit

class ViewController: UIViewController {
    @IBOutlet weak var mapView: MKMapView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Set initial location
        let initialLocation = CLLocation(latitude: 37.3318, longitude: -122.0296)
        centerMapOnLocation(location: initialLocation)
    }
    
    func centerMapOnLocation(location: CLLocation, regionRadius: CLLocationDistance = 1000) {
        let coordinateRegion = MKCoordinateRegion(center: location.coordinate,
                                                  latitudinalMeters: regionRadius,
                                                  longitudinalMeters: regionRadius)
        mapView.setRegion(coordinateRegion, animated: true)
    }
}

5. Displaying User Location

To display the user’s location, we use CLLocationManager. CLLocationManager is an object used to collect location information. Add CLLocationManager to the ViewController and implement the CLLocationManagerDelegate protocol in the ViewController.

import UIKit
import MapKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {
    @IBOutlet weak var mapView: MKMapView!
    let locationManager = CLLocationManager()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        locationManager.delegate = self
        locationManager.requestWhenInUseAuthorization()
        locationManager.startUpdatingLocation()
    }
    
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let location = locations.last else { return }
        centerMapOnLocation(location: location)
    }
}

6. Adding Markers (Pins)

Let’s add a marker to the map view. To add a marker, we use MKPointAnnotation. We will implement a method to add a pin at a specific location.

func addAnnotation(latitude: Double, longitude: Double, title: String, subtitle: String) {
    let annotation = MKPointAnnotation()
    annotation.coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
    annotation.title = title
    annotation.subtitle = subtitle
    mapView.addAnnotation(annotation)
}

// Adding a marker
addAnnotation(latitude: 37.3318, longitude: -122.0296, title: "Apple Park", subtitle: "Apple's headquarters")

7. Implementing Various Map View Features

7.1. Setting the Appropriate Map Type

To set the type of the map view, simply set the mapView.mapType property. You can choose types such as standard (panoramic), satellite, hybrid, etc.

mapView.mapType = .satellite // Set to satellite map

7.2. Displaying Routes

To display the route between two points, you can use MKDirections to calculate the route. Create a route between the user’s selected starting point and destination and display it on the map view.

func getDirections(source: CLLocationCoordinate2D, destination: CLLocationCoordinate2D) {
    let sourcePlacemark = MKPlacemark(coordinate: source)
    let destinationPlacemark = MKPlacemark(coordinate: destination)
    
    let request = MKDirections.Request()
    request.source = MKMapItem(placemark: sourcePlacemark)
    request.destination = MKMapItem(placemark: destinationPlacemark)
    request.transportType = .automobile
    
    let directions = MKDirections(request: request)
    directions.calculate { response, error in
        guard let response = response else {
            if let error = error {
                print("Error calculating directions: \(error.localizedDescription)")
            }
            return
        }
        
        let route = response.routes[0]
        self.mapView.addOverlay(route.polyline, level: .aboveRoads)
    }
}

override func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
    if let polylineRenderer = overlay as? MKPolyline {
        let renderer = MKPolylineRenderer(polyline: polylineRenderer)
        renderer.strokeColor = UIColor.blue
        renderer.lineWidth = 5
        return renderer
    }
    return MKOverlayRenderer(overlay: overlay)
}

8. Finalizing and Distributing

Now we can finalize the app based on the map view features we implemented. Build the app and test it on the simulator or a real device, checking the location information and map functionalities. If all features work correctly, you can distribute the app to the App Store and share it with users.

In this post, we explored how to implement a map view in an iPhone app using Swift and UIKIT. Swift is a powerful and intuitive language, offering many possibilities for app developers. I encourage you to use Swift with UIKIT to create feature-rich apps.

If you found this post helpful, please leave a comment and like it! If you have any additional questions, feel free to leave them in the comments.

Developing iPhone Apps with Swift and UIKit: Creating a Simple Web Browser using Web View

iPhone app development has become an essential skill for many developers. In particular, using the Swift language and UIKit framework to develop iOS applications is very common. In this post, we will explore the basic methods for developing iPhone apps using UIKit, and how to create a simple web browser using UIWebView or WKWebView.

1. Setting Up the iOS Development Environment

To start iOS app development, you need to install the following tools:

  • Xcode installation: A free app that can only be used on macOS, it is essential for developing iPhone and iPad apps.
  • Swift Language: A programming language created by Apple, effective for developing iOS, macOS, watchOS, and tvOS applications.
  • An iPhone or iPad for development: You can test apps on a real device. Virtual devices are also possible, but real testing is important.

2. Understanding the Basic UIKit Structure

UIKit provides various components necessary to construct the user interface of the application. You can design an app to interact with users using various components like UIViewController, UIView, UILabel, UIButton, etc.

2.1. UIViewController

Most iOS apps are built on top of UIViewController. UIViewController is a class that represents a screen. Each view controller manages a view and its data and handles user input.


class MyViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        // Method called when the view is loaded
    }
}

2.2. UIView

UIView represents a rectangular area on the screen and is the fundamental unit that makes up each element. UI components such as buttons, labels, and images are created by inheriting from UIView.

3. Creating a Web Browser Using WKWebView

Now let’s create a simple web browser using a web view. WKWebView is a class used to display web content provided by Apple. It performs better than UIWebView.

3.1. Creating a Project

Open Xcode and create a new project. Select the “App” template, set the language to Swift, and choose UIKit. Name your project and proceed.

3.2. Adding WKWebView

Let’s create a simple UI in the storyboard. Add a WKWebView to the screen and adjust its position using NSLayoutConstraints.


// Import UIKit and WebKit
import UIKit
import WebKit

class MyWebViewController: UIViewController {
    var webView: WKWebView!

    override func loadView() {
        webView = WKWebView()
        view = webView
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Load the desired URL
        let url = URL(string: "https://www.apple.com")!
        webView.load(URLRequest(url: url))
    }
}

4. Receiving User Input

In the web browser, you can implement functionality that allows users to directly enter a URL. For this, we will add a UITextField to load the URL entered by the user.


class MyWebViewController: UIViewController {
    var webView: WKWebView!
    var textField: UITextField!

    override func loadView() {
        let containerView = UIView()
        webView = WKWebView()
        textField = UITextField()
        textField.borderStyle = .roundedRect

        containerView.addSubview(textField)
        containerView.addSubview(webView)

        textField.translatesAutoresizingMaskIntoConstraints = false
        webView.translatesAutoresizingMaskIntoConstraints = false

        NSLayoutConstraint.activate([
            textField.topAnchor.constraint(equalTo: containerView.topAnchor, constant: 20),
            textField.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: 20),
            textField.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: -20),
            webView.topAnchor.constraint(equalTo: textField.bottomAnchor, constant: 20),
            webView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor),
            webView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor),
            webView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor)
        ])

        view = containerView
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Load the default URL
        let url = URL(string: "https://www.apple.com")!
        webView.load(URLRequest(url: url))
        setupTextFieldAction()
    }

    private func setupTextFieldAction() {
        textField.addTarget(self, action: #selector(loadWebPage), for: .editingDidEndOnExit)
    }

    @objc func loadWebPage() {
        guard let urlString = textField.text, let url = URL(string: urlString) else { return }
        webView.load(URLRequest(url: url))
    }
}

5. Designing Additional Features for the App

Let’s implement additional features in the web browser. It’s good to add functionality for the user to refresh the page and navigate back and forward. To do this, we will add three UIButton.


override func loadView() {
    let containerView = UIView()
    webView = WKWebView()
    textField = UITextField()
    textField.borderStyle = .roundedRect

    let refreshButton = UIButton(type: .system)
    let backButton = UIButton(type: .system)
    let forwardButton = UIButton(type: .system)

    refreshButton.setTitle("Refresh", for: .normal)
    backButton.setTitle("Back", for: .normal)
    forwardButton.setTitle("Forward", for: .normal)

    containerView.addSubview(textField)
    containerView.addSubview(webView)
    containerView.addSubview(refreshButton)
    containerView.addSubview(backButton)
    containerView.addSubview(forwardButton)

    // Auto Layout setting omitted...

    refreshButton.addTarget(self, action: #selector(refreshPage), for: .touchUpInside)
    backButton.addTarget(self, action: #selector(goBack), for: .touchUpInside)
    forwardButton.addTarget(self, action: #selector(goForward), for: .touchUpInside)
}

@objc func refreshPage() {
    webView.reload()
}

@objc func goBack() {
    if webView.canGoBack {
        webView.goBack()
    }
}

@objc func goForward() {
    if webView.canGoForward {
        webView.goForward()
    }
}

Conclusion

In this article, we explored how to create a simple web browser using Swift and UIKit. Based on an understanding of basic UIKit components, we learned how to handle WKWebView and user input. I hope this example serves as a good foundation for grasping the fundamental concepts of iOS app development and that you can expand your app through additional features.

Continue to enhance your use of Swift and UIKit through a variety of projects. Happy Coding!

Using Swift for UIKit Method, Developing iPhone Apps, 06 Displaying Alerts to Show Warnings

In iPhone app development, configuring the user interface (UI) is a very important element. Especially, delivering specific situations or warning messages to users is essential. Let’s learn how to effectively use alerts to display warnings by utilizing the Swift language and the UIKit framework.

1. The Concept of Alert

An alert is a dialog box that displays specific information to the user and prompts user actions. It is mainly used for warnings, confirmation requests, and information delivery. Alerts attract the user’s attention and allow the app’s flow to be determined based on the selected actions.

2. Introduction to the UIKit Framework

UIKit is Apple’s app development support framework, primarily used for building the user interface of iPhone and iPad applications. When developing in Swift, you can easily configure various UI elements such as buttons, labels, images, and alerts using UIKit.

3. Basic Usage of Alerts

Creating an alert in Swift is simple. Using UIAlertController, you can easily create various types of alerts. Here, we’ll explain how to create a basic alert.

3.1 Initializing UIAlertController

To create an alert, you need to initialize it using UIAlertController. The following is the code to create a basic alert:

let alert = UIAlertController(title: "Warning", message: "An issue has occurred!", preferredStyle: .alert)

3.2 Adding Actions

You need to add actions to the alert to provide options for users to choose from. The code below shows how to add a “Confirm” button:

alert.addAction(UIAlertAction(title: "Confirm", style: .default, handler: nil))

3.3 Displaying the Alert

Finally, display the alert on the screen. To do this, call the present() method through the current view controller:

self.present(alert, animated: true, completion: nil)

4. Various Forms of Alerts

Alerts can be implemented in various forms beyond the basic type. For example, you can add an input field. The following code can be used for this purpose:

let inputAlert = UIAlertController(title: "Enter Name", message: "Please enter your name.", preferredStyle: .alert)
inputAlert.addTextField { (textField) in
    textField.placeholder = "Name"
}
inputAlert.addAction(UIAlertAction(title: "Confirm", style: .default, handler: { (action) in
    let name = inputAlert.textFields?.first?.text
    print("User entered name: \(name ?? "")")
}))
self.present(inputAlert, animated: true, completion: nil)

5. Customizing Alerts

If you want to make alerts more appealing, you can apply custom designs. Let’s learn how to change the button colors, font styles, and more. However, modifying the style of the basic alert is limited in UIKit. Instead, you cannot change the style of UIAlertController.

5.1 Adjusting UIButton Styles

To apply your own button styles, you can use a custom UIButton and add it to the view:

let customButton = UIButton(type: .system)
customButton.setTitle("Confirm Creation", for: .normal)
customButton.addTarget(self, action: #selector(customButtonTapped), for: .touchUpInside)
self.view.addSubview(customButton)

5.2 Alternative Designs for Alerts

As an alternative to UIAlertController, you can subclass UIViewController to create your desired design directly. In this case, create a custom view to represent the alert and arrange the buttons and text fields as you wish.

6. Using Alerts in Applications

These alerts are used in various situations within an app. For example, when a user tries to modify important information, you can request their confirmation with an alert that says, “Do you really want to make the change?” Here is an example code:

let changeAlert = UIAlertController(title: "Change Confirmation", message: "Do you want to save the changes?", preferredStyle: .alert)
changeAlert.addAction(UIAlertAction(title: "Yes", style: .default, handler: { (action) in
    // Logic to save changes
}))
changeAlert.addAction(UIAlertAction(title: "No", style: .cancel, handler: nil))
self.present(changeAlert, animated: true, completion: nil)

7. Conclusion

Alerts play a crucial role in facilitating communication with users in app development using Swift and UIKit. They help effectively convey the necessary information to users. This tutorial covered basic alert usage to various forms of alert usage.

Now you can create alerts using Swift and enhance the user experience of your app. Explore using alerts in various scenarios!

Using UIKit style in Swift, iPhone app development, 05 Choosing desired items using Picker View

1. Introduction

Swift is a modern programming language used for developing applications in the Apple ecosystem. With its fast, safe, and modern syntax, Swift plays a crucial role in iOS application development. UIKit is a framework for constructing and managing user interfaces, providing various UI components.

In this blog, we will explore one of the components of UIKit, the Picker View. The Picker View is a UI element that provides a selection of options to the user and allows easy reflection of the selected value. For example, it is useful for date pickers or selecting items from a list. We will learn how to create and use a Picker View with the Swift language.

2. What is a Picker View?

A Picker View is a view that allows the user to select from multiple items. It typically appears as a scrollable list, where users can scroll with their finger to make a selection. It offers similar functionality to Android’s Spinner or iOS’s UIAlertController but provides a more intuitive and user-friendly interface.

iOS’s Picker View has two basic types.

  • UIPickerView: It generally creates a 2D selector that allows items to be selected by scrolling vertically.
  • UIDatePicker: A special Picker for date and time selection, helping users to choose more specific dates and times.

3. Basic Structure of UIPickerView

UIPickerView operates similarly to UITableView, but each item displays important values for selection. To use UIPickerView, several protocols need to be implemented, following the data source protocol and delegate.


            class MyViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
                var pickerView: UIPickerView!
                var items: [String] = ["Apple", "Banana", "Cherry", "Date", "Elderberry"]
                
                override func viewDidLoad() {
                    super.viewDidLoad()
                    
                    pickerView = UIPickerView()
                    pickerView.dataSource = self
                    pickerView.delegate = self
                    
                    view.addSubview(pickerView)
                }

                // UIPickerView DataSource Methods
                func numberOfComponents(in pickerView: UIPickerView) -> Int {
                    return 1
                }

                func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
                    return items.count
                }
            }
            

4. Configuring UIPickerView and Displaying Items

The items to be displayed in the UIPickerView are stored in the ‘items’ array. The ‘numberOfComponents’ method returns the number of columns in the Picker View, and the ‘numberOfRowsInComponent’ method returns the number of items in each column.

Now, to display each item, we need to implement the pickerView(_:titleForRow:forComponent:) method. This method provides the title of the item to be displayed in each row of the Picker View.


            func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
                return items[row]
            }
            

5. Handling Item Selection

When a user selects an item from the UIPickerView, actions can be taken based on the selected value. To retrieve the selected item, we implement the pickerView(_:didSelectRow:inComponent:) method.


            func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
                let selectedItem = items[row]
                // Logic to handle the selected item
                print("Selected item: \(selectedItem)")
            }
            

6. UI Customization

The Picker View is provided in its basic form, but it can be customized in various ways. For instance, custom views can be provided for each item. To do this, we use the pickerView(_:viewForRow:forComponent:reusing:) method.


            func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
                let label = UILabel()
                label.text = items[row]
                label.textAlignment = .center
                // Additional styling
                return label
            }
            

7. Using UIDatePicker

UIDatePicker is a picker that can be used to set specific dates and times. UIDatePicker supports various styles when created and can be used in date or time format. It can be simply utilized as shown in the code example below.


            @IBOutlet weak var datePicker: UIDatePicker!

            override func viewDidLoad() {
                super.viewDidLoad()

                // Configuring UIDatePicker
                datePicker.datePickerMode = .date
            }

            @IBAction func dateChanged(_ sender: UIDatePicker) {
                let selectedDate = sender.date
                // Logic to handle the selected date
                print("Selected date: \(selectedDate)")
            }
            

8. Integrating Picker View into a Real App

Now we will demonstrate how to set up UIPickerView and UIDatePicker and integrate them into a real application without omitting any steps. Based on the view controller we have created, selected items and dates can be easily reflected or saved to other UI elements.

For example, here is a code snippet that displays the selected fruit name on a UILabel.


            @IBOutlet weak var selectedFruitLabel: UILabel!
            
            func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
                let selectedItem = items[row]
                selectedFruitLabel.text = "Selected fruit: \(selectedItem)"
            }
            

9. Conclusion

In this post, we learned how to implement UIPickerView and UIDatePicker using Swift and UIKit. We learned how to build a user-friendly interface and control the app’s behavior based on selected items.

The Picker View is a very useful tool that enriches the user experience of the app and helps users easily select the necessary information. It can be beneficial in various scenarios, so we encourage you to customize and implement it in a way that fits your application.