A
A
alex_6432020-06-02 10:56:00
iOS
alex_643, 2020-06-02 10:56:00

How to add a button to a specific view controller via code?

Hello! I want to click a button on one VC and add an element to another via code. How can this be implemented?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladislav Resley, 2020-06-02
@alex_643

If I understood everything correctly, you need to pass data between controllers using segue.
We create a variable in the class of the second controller, to which we will pass the desired value.
Next, create a button on the first controller and drag the segway from the button to the second controller. and specify its identifier.
Below is the code for the second controller. Just a Label, and assign the value of the "name" variable to the "text" property of this label.

class SecondViewController: UIViewController {

    var name = ""
    
    @IBOutlet var username: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        username.text = name
    }
}

Here is the code of the first controller using the prepare(for segue:) method, we get access to the controller to which we pass through this segway. You can get access through destination. Next, we pass the name to our variable that we created in the class of the second controller, for example Andrey. And this method will work before switching to the second controller, and will pass "Vasya" to our "name" variable, when the second controller is launched, the label will take the value from this variable and fill in its "text" property
class FirstViewController: UIViewController {

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

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        guard segue.identifier == "YourIdentificator" else { return }
        guard let destination = segue.destination as? SecondViewController else { return }
        destination.name = "Вася"
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question