我通过情节提要创建了12个UIButton,在我的程序中,这些按钮代表卡片,我希望随机改变按钮的位置以洗牌。请帮我一个忙,给出实现该想法的方法或想法。
导入UIKit
ViewController类:UIViewController {
lazy var game = Concentration(numberOfPairsOfCards: numberOfPairOfCards) //引入model Concentration
var numberOfPairOfCards : Int {
return (cardButtons.count + 1) / 2 //read only computed properties可以省略get{}
}
var flipCount = 0 {
didSet {
flipsCountLabel.text = "Flips: \(flipCount)"
}
}
@IBOutlet var cardButtons: [UIButton]!
@IBOutlet weak var flipsCountLabel: UILabel!
@IBAction func touchCard(_ sender: UIButton) {
flipCount += 1
if let cardNumber = cardButtons.index(of: sender) {
game.chooseCard(at: cardNumber)
updateViewFromModel()
} else {
print("somthing wrong")
}
}
我已经完成了工作。
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var buttons = [UIButton]()
for index in cardButtons.indices {
buttons.append(cardButtons[index])
}
for index in cardButtons.indices {
cardButtons[index] = buttons.remove(at: buttons.count.arc4random)
}
}
答案 0 :(得分:0)
您可以将按钮添加到数组中,将数组随机排列,然后遍历数组并放置按钮。更好的解决方案是创建一个UICollectionView。