我正在制作纯粹的猜纸牌游戏,每次选择正确的牌时,新的按钮/牌将出现在屏幕上。我已经制作了addButton函数,但我对我必须放入的内容感到困惑。任何人都可以引导我朝着正确的方向指导每次调用函数时我应该如何创建一个新按钮。
let card1 = UIButton(type: UIButtonType.Custom) as UIButton
let card2 = UIButton(type: UIButtonType.Custom) as UIButton
var random = arc4random_uniform(101)
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
card1.backgroundColor = UIColor.cyanColor()
card1.frame = CGRectMake(100, 100, 100, 100)
card1.addTarget(self, action: "Card1Btn:", forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(card1)
card2.backgroundColor = UIColor.cyanColor()
card2.frame = CGRectMake(500, 100, 100, 100)
card2.addTarget(self, action: "Card2Btn:", forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(card2)
}
func Card1Btn(sender: UIButton!){
if random <= 50{
print("you won")
}else{
print ("you Lost")
}
}
func Card2Btn(sender: UIButton!){
if random >= 51{
print("you won")
}else{
print("you lost")
}
}
func addButton(){
}
答案 0 :(得分:1)
您已经有代码在viewDidLoad
中添加按钮,因此请让它可重复使用。首先,我们需要制作您的card1
和card2
引用变量,以便我们可以跟踪我们将要创建的新卡片......
var card1 = nil as UIButton?
var card2 = nil as UIButton?
另外,由于添加按钮的代码可以重复使用,我们不想重复自己,所以让我们为卡片1和卡片2的帧添加一些常量... < / p>
let card1Frame = CGRectMake(100, 100, 100, 100)
let card2Frame = CGRectMake(500, 100, 100, 100)
我们可以将添加按钮代码(以前在viewDidLoad
中重复)添加到自己的函数中...
func addButtonWithFrame(frame: CGRect) -> UIButton
{
let card = UIButton(type: UIButtonType.Custom) as UIButton
card.backgroundColor = UIColor.cyanColor()
card.frame = frame
card.addTarget(self, action: #selector(MyVC.cardButtonPressed(_:)), forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(card)
return card
}
现在我们有了创建和添加按钮的通用方法,让我们在viewDidLoad
中使用它...
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
card1 = self.addButtonWithFrame(card1Frame)
card2 = self.addButtonWithFrame(card2Frame)
}
现在我们可以在按下按钮时重复使用相同的代码......
func cardButtonPressed(sender: UIButton!){
// Decide on win or lose based on current value of 'random'
if random <= 50{
print("you won")
}else{
print("you Lost")
}
// Set a new value for 'random' ready for next time
random = arc4random_uniform(101)
// Remove old card
sender.removeFromSuperview()
// Generate new replacement card
let newFrame = sender.frame
let newCard = self.addButtonWithFrame(newFrame)
// Keep reference to new card
if (sender == card1){
card1 = newCard
}else{
card2 = newCard
}
}