简体   繁体   中英

Change button title when clicking it

class ViewController: UIViewController {

    @IBOutlet weak var words: UILabel!

    var positiveWords = ["dont give up","keep going","you can do that","your are strong"]

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }


    @IBAction func wordsButton(_ sender: Any) {

        for w in positiveWords {

         // show array in label
            words.text = "\(w)" 

        }

    }
}

When I click the button it shows only one word but I want to show another word while clicking, how can I do this?

a word which is displayed to a user is the last one of the positiveWords array of a Strings because you use a control flow For-In Loop which enumerate the array and set a current element to a label.

Solution:

Standard Library Array function joined(separator:)

@IBAction
func wordsButton(_ sender: Any) {

    words.text = positiveWords.joined(separator: ", ")

}

For-In Loop

func wordsButton(_ sender: Any) {

    var labelWord: String = ""
    for word in positiveWords {
        labelWord = labelWord + ", " + word
    }
    words.text = labelWord
}

Your question is a bit vague. But here is different ways to solve your problem

//Wil generate different word every time you press the button
   func wordsButton(_ sender: Any) { 
        words.text = positiveWords.randomElement(
   } 

if you want to add the whole array at once

  func wordsButton(_ sender: Any) { 
     for w in positiveWords {
            words.text! += "\(w) "
        } 
  } 

if you want to add one at a time

var displayedWords = o
  func wordsButton(_ sender: Any) { 
     var totalWords = positiveWords.count
        if displayedWords < totalWords {
            label.text! += "\(positiveWords[displayedWords]) "
            displayedWords += 1
        }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM