0

Hi I'm a beginner in Swift and I would like to know how I can make string values, stored in an array, the title of buttons.

Specific to my case: I have 24 buttons in my storyboard, all put into one action in the controller view. In my model I have an array with 24 emoji's and I would like to know how I can (randomly) assign these emoji's to my buttons.

var emoji : [String] = ["🦁","🦁", "🐶","🐶", "🐱", "🐱", "🐭", "🐭", "🐹", "🐹", "🐰", "🐰", "🐻", "🐻", "🐼", "🐼", "🐨", "🐨", "🐯","🐯", "🐮", "🐮", "🐷", "🐷"]

Thank you in advance.

2
  • You could shuffle the emoji array, and thereafter sequentially set the label of the i:th button to the i:th entry in the emoji array, for i ranging over your 24 buttons. Commented Mar 31, 2017 at 21:02
  • Fun fact, GameKit has a built in array shuffle function let shuffledEmoji = GKRandomSource.sharedRandom().arrayByShufflingObjects(in: emoji) which could help with this. Commented Mar 31, 2017 at 21:48

3 Answers 3

1

When connecting the buttons to the code, connect them as an Outlet Connection. Then you will have an array of buttons. To set the button text accordingly:

for button in buttons {
    button.setTitle(emoji[buttons.index(of: button)!], for: [])
}

This will loop through all the buttons and set their title to the corresponding emojis. You can look at how to shuffle an array to randomize the emoji: How do I shuffle an array in Swift?

Sign up to request clarification or add additional context in comments.

Comments

0

Assuming you've added buttons to a view e.g. via interface builder you can do something like this. There are a lot of examples on how to sort the emoji array elsewhere.

class ViewController: UIViewController {

    let emoji = ["🦁","🦁", "🐶","🐶", "🐱", "🐱", "🐭", "🐭", "🐹", "🐹", "🐰", "🐰", "🐻", "🐻", "🐼", "🐼", "🐨", "🐨", "🐯","🐯", "🐮", "🐮", "🐷", "🐷"]

    override func viewDidLoad() {
        super.viewDidLoad()
        let buttons: [UIButton] = view.subviews.flatMap { $0 as? UIButton }
        guard buttons.count <= emoji.count else {
            fatalError("Not enough emoji for buttons")
        }
        // sort emoji here
        _ = buttons.enumerated().map {  (index, element) in
            element.setTitle(emoji[index], for: .normal)
        }
    }
}

Comments

0

This solution leverages shuffled() and zip()

class MyViewController: UIViewController {

    // Add the face buttons to the collection in the storyboard
    @IBOutlet var faceButtons: [UIButton]!
    let faces = ["🦁","🦁", "🐶","🐶", "🐱", "🐱", "🐭", "🐭", "🐹", "🐹", "🐰", "🐰", "🐻", "🐻", "🐼", "🐼", "🐨", "🐨", "🐯","🐯", "🐮", "🐮", "🐷", "🐷"]

    func randomizeFaces() {
        // zip() combines faceButtons and faces, shuffled() randomizes faces
        zip(faceButtons, faces.shuffled()).forEach { faceButtton, face in
            faceButtton.setTitle(face, for: .normal)
        }
    }

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

}

Here is the definition of shuffled() from: How do I shuffle an array in Swift?

extension MutableCollection where Indices.Iterator.Element == Index {
    /// Shuffles the contents of this collection.
    mutating func shuffle() {
        let c = count
        guard c > 1 else { return }

        for (firstUnshuffled , unshuffledCount) in zip(indices, stride(from: c, to: 1, by: -1)) {
            let d: IndexDistance = numericCast(arc4random_uniform(numericCast(unshuffledCount)))
            guard d != 0 else { continue }
            let i = index(firstUnshuffled, offsetBy: d)
            swap(&self[firstUnshuffled], &self[i])
        }
    }
}

extension Sequence {
    /// Returns an array with the contents of this sequence, shuffled.
    func shuffled() -> [Iterator.Element] {
        var result = Array(self)
        result.shuffle()
        return result
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.