[Swift] How to pass the Label value in the selected collectionViewCell to the destination TextField

Introduction

This time I would like to record how to pass the Label value in the collectionViewCell selected by tapping to the TextField of the transition destination in the transition using segue. By the way, the screen transition is done using NavigationController and segue.

Development environment

macOS 11.0.1
Xcode version 12.2
Swift version 5.3.1

What you want to implement

As a premise

First, before writing the code to pass the value, [a] [i] [a] [e] [o] are assigned to the labels of each of the five cells in the following state. .. I would like to write a code that passes the contents of the selected cell to the transition destination, such as [A] when pressing the [A] cell and [I] when pressing the [I] cell.

FirstViewContoroller


import UIKit

class ViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource{

    @IBOutlet weak var collectionView: UICollectionView!
    
    var array = ["Ah","I","U","e","O"] //The number of arrays this time is 5

    override func viewDidLoad() {
        super.viewDidLoad() 
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

         return array.count //Set the number of cells to the number of arrays

    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for:indexPath)
        //Put the String value of array in Label in the tagged Cell
        var arrayLabel = cell.contentView.viewWithTag(1) as! UILabel
        arrayLabel.text = array[indexPath.row] 
        
        return cell
    }
}

Add the following code to the transition source Controller

FirstViewController


    //Receive the selected label value
    var selectedArray:String?
   
    //Write the behavior when cell is selected with didSelectItemAt
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        //The label in the selected Cell is assigned to selectedArray
        selectedArray = array[indexPath.row]
        //Screen transition
        performSegue(withIdentifier: "toNext", sender: nil)

    }

    //Preparing segue
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        
        let nextVC = segue.destination as? NextViewController
        //Pass the transition source selectedArray to the transition destination selectedLabel
        nextVC?.selectedLabel = selectedArray
     
    }

Write in the transition destination NextViewController

NextViewController


import UIKit


class NextViewController: UIViewController {

    @IBOutlet weak var textFiled: UITextField! 
    //The value selected in the transition source comes in
    var selectedLabel:String?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //Pass the passed value to TextFiled
        textFiled.text = selectedLabel
        
    }

By writing in this way, the label value in the selected cell can be passed to the transition destination.

Common mistakes

In NextViewController, ** var selectedLabel: String? ** is set as an instance variable, and the value of the transition source is passed to it. However, you may think that you can pass the value directly to textFiled instead. I was the same. This method is wrong. When I actually write it, build it, and select a cell, I get the error ** Unexpectedly found nil while implicitly unwrapping an Optional value **. Simply put, there is an unexpected nil! is what it means. To put it simply, nil means empty. This is probably because the instance of the UITextFiled part of the transition destination does not exist when trying to pass the acquired value of the transition source to the textFiled of the transition destination.

Referenced site

https://capibara1969.com/1060/

Summary

This time it was about how to pass the value at the time of screen transition, but I will update what I learned from time to time! If you find it helpful, please use LGTM! !!

Recommended Posts

[Swift] How to pass the Label value in the selected collectionViewCell to the destination TextField
[Swift] How to fix Label in UIPickerView
How to pass the value to another screen
How to add sound in the app (swift)
How to retrieve the hash value in an array in Ruby
How to disable existing selected items in the select box
Pass the i18n locale to JavaScript
How to output the value when there is an array in the array
[Swift5] How to communicate from ViewController to Model and pass a value
How to increment the value of Map in one line in Java
[swift5] How to specify color in hexadecimal
Shorten the UUID to base64 in Swift.
[Swift] How to implement the countdown function
How to get the date in java
How to overwrite Firebase data in Swift
How to return a value from Model to Controller using the [Swift5] protocol
How to get the value after "_" in Windows batch like Java -version
How to constrain the action of the transition destination when not logged in
How to get the setting value (property value) from the database in Spring Framework
How to change the value of a variable at a breakpoint in intelliJ
[Swift] How to set an image in the background without using UIImageView.
Android development, how to check null in the value of JSON object
How to create your own annotation in Java and get the value
[Swift] How to reflect the array changed at the transition destination to the transition source and display it on Label etc.
[Swift] How to get the number of elements in an array (super basic)
[Rails] How to decide the destination by "rails routes"
How to check the logs in the Docker container
How to get the ID of a user authenticated with Firebase in Swift
[Swift] How to implement the LINE login function
[swift5] How to implement the Twitter share function
[Swift] How to link the app with Firebase
[Swift] How to change the order of Bar Items in Tab Bar Controller [Beginner]
[Swift] How to implement the fade-in / out function
How to execute tasks in parallel in Swift in Swift Package
How to build the simplest blockchain in Ruby
How to check Rails commands in the terminal
I want to get the value in Ruby
[Swift] How to simply describe dismiss that was not taught in the introductory book
[Java] How to get the key and value stored in Map by iterative processing
How to check if the characters entered in the Swift Text Field are email addresses
[Swift] How to display the entered characters in Widget via UserDefaults when using WidgetKit
How to implement UICollectionView in Swift with code only
How to set the display time to Japan time in Rails
[Java] How to omit the private constructor in Lombok
How to send value in HTML without screen transition
[Java] How to get the maximum value of HashMap
Organized how to interact with the JDK in stages
[Swift] Use UserDefaults to save data in the app
How to specify the resource path in HTML import
Find the approximate value of log (1 + x) in Swift
How to debug the generated jar file in Eclipse
[Swift] How to get the document ID of Firebase
[Rails] How to display an image in the view
[How to use label]
How to specify an array in the return value / argument of the method in the CORBA IDL file
How to solve the problem when the value is not sent when the form is disabled in rails and sent
How to correctly check the local HTML file in the browser
How to use the getter / setter method (in object orientation)
How to transition from the [Swift5] app to the iPhone settings screen
How to set chrony when the time shifts in CentOS7
How to pass an object to Mapper in MyBatis without arguments