如何在Swift中将数组中的值赋给按钮

时间:2017-03-31 20:53:33

标签: arrays swift swift3

嗨,我是Swift的初学者,我想知道如何创建字符串值,存储在数组中,按钮的标题。

具体到我的情况:我的故事板中有24个按钮,所有按钮都在控制器视图中进行了一次操作。在我的模型中,我有一个包含24个表情符号的数组,我想知道如何(随机)将这些表情符号分配给我的按钮。

var emoji : [String] = ["","", "","", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "","", "", "", "", ""]

提前谢谢。

3 个答案:

答案 0 :(得分:1)

将按钮连接到代码时,请将它们作为插座连接连接。然后你将有一系列按钮。相应地设置按钮文本:

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

这将遍历所有按钮并将其标题设置为相应的表情符号。您可以查看如何对数组进行随机化以随机化表情符号:How do I shuffle an array in Swift?

答案 1 :(得分:0)

假设您已向视图添加按钮,例如通过界面构建​​器,你可以做这样的事情。关于如何在其他地方对表情符号数组进行排序有很多例子。

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)
        }
    }
}

答案 2 :(得分:0)

此解决方案利用shuffled()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()
    }

}

以下是来自How do I shuffle an array in Swift?

shuffled()的定义
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
    }
}