2017-03-31 51 views
0

嗨,我是Swift的初學者,我想知道如何創建字符串值,存儲在數組中,按鈕的標題。如何從數組中分配值到Swift中的按鈕

具體到我的情況:我有我的故事板中的24個按鈕,所有在控制器視圖中放入一個動作。在我的模型中,我有一個包含24個表情符號的數組,我想知道如何(隨機)將這些表情符號分配給我的按鈕。

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

在此先感謝您。

+0

你可以[洗牌'emoji'數組](http://stackoverflow.com/questions/24026510/how-do-i-shuffle-an-array-in-swift),然後依次設置'i'的標籤:th按鈕到'e'中的'i':th條目moji'數組,對於'i'來說,可以覆蓋24個按鈕。 – dfri

+0

有趣的是,GameKit有一個內置的數組shuffle函數'let shuffledEmoji = GKRandomSource.sharedRandom()。arrayByShufflingObjects(in:emoji)''可以幫助解決這個問題。 –

回答

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

當按鈕連接到所述代碼,將它們連接爲出口連接。然後你將有一個按鈕陣列。要相應地設置按鈕文字:

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

這將遍歷所有按鈕並將其標題設置爲相應的表情符號。你可以看一下如何洗牌數組隨機表情符號:How do I shuffle an array in Swift?

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

} 

這裏是shuffled()自定義: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 
    } 
}