Search code examples
iosswiftuibuttonuikitprogrammatically-created

How to programmatically receive input from UIButton in Swift 4?


I'm new to Swift. I managed to build an app which almost works, but I cannot get the last steps right. I would appreciate any help!

I wrote a code which displays a user-defined number of UILabels. In those labels, the contents of a [String] is displayed. Under the labels, there is the same number of UITextFields. The user should fill out these text fields, press the button and then see if what he filled out matches the labels.

All the labels, the text fields, and the button are made completely programmatically, so without using the storyboard. In the viewDidLoad there is all the code and this line:

myButton.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)

Right under viewDidLoad there is this function which I found on this forum and I changed it a bit:

@objc func buttonAction(sender: UIButton!) -> [String] {
    var a = 0
    var userInput: [String] = Array()
    while a < 4 {
        if let myTextField = self.view.viewWithTag(a) as? UITextField {
            let tekstInput = myTextField.text
            userInput.insert(tekstInput!, at:a-1)
        }
        a = a + 1
    }
    return userInput
}

My problems:

The while-loop in the function shouldn't have 4 as the maximum, but a user-defined variable. But if I try to change function so that it expects that variable as an input, I get error messages in the myButton.addTarget line.

How do I read out the return in the viewdidload to add there the code to compare the user input with the original [String]?


Solution

  • You should consider the source of the user-defined input if you want to answer your question.

    For instance, if you are willing to add an extra UITextField to retrieve your user input, then all you have to do is extract the value from that text field within your buttonAction(sender:) method and use it there. This translates roughly to the following

    @objc func buttonAction(_ sender: UIButton) {
    
        var a = 0
        var userInput: [String] = Array()
    
        guard let upperLimit = self.userInputTextField.text as? Int else {
            return
        }
    
        while a < upperLimit {
            if let myTextField = self.view.viewWithTag(a) as? UITextField {
                let tekstInput = myTextField.text
                userInput.insert(tekstInput!, at: a-1)
            }
            a = a + 1
        }
    
    }
    

    Note that self.userInputTextField is the extra text field you should add in order to retrieve your user-defined input.