我正在尝试将一个字符串从一个if语句传递给另一个。我已经在两个if语句之外声明了var,现在只有占位符字符串。
应该发生的是,按一下按钮,它会显示按钮的标题(想想计算器上的按钮/数字)。当第二次点击按钮时,它应显示第一个按钮的标题和按下的第二个按钮的标题,以便创建一个两位数的数字。
实际发生的是它正确显示第一个按钮,但是一旦第二个按钮被按下,它会显示第一个按钮作为占位符字符串。
代码如下。任何帮助都会很棒!
app + code的屏幕截图..新卡旁边应该是“21”而不是“place 1”http://imgur.com/vMmciyh
@IBAction func oneButtonPressed(sender: AnyObject)
{
timesButtonPressed += 1
var buttonTitle1:String! = ("Place ")
var buttonTitle2:String! = ("holder")
if timesButtonPressed == 1
{
buttonTitle1 = sender.titleLabel!?.text
self.answerTyped.text = String (buttonTitle1)
}
if timesButtonPressed == 2
{
buttonTitle2 = sender.titleLabel!?.text
self.answerTyped.text = String (stringInterpolation: buttonTitle1, buttonTitle2)
}
}
完整代码:
导入UIKit
类PlayViewController:UIViewController {
@IBOutlet weak var newCardButton: UIButton!
@IBOutlet weak var labelTest: UILabel!
@IBOutlet weak var oneButton: UIButton!
@IBOutlet weak var answerTyped: UILabel!
@IBOutlet weak var enterButton: UIButton!
var mathProblem = String ("Answer Typed")
var firstRandomNumber = 0
var secondRandomNumber = 0
var buttonName = String ("button name")
var timesButtonPressed = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func newCardButtonPressed(sender: AnyObject)
{
firstRandomNumber = Int(arc4random_uniform(11))
secondRandomNumber = Int(arc4random_uniform(11))
mathProblem = String(format:"%i x %i", firstRandomNumber, secondRandomNumber)
self.labelTest.text = String (mathProblem)
}
@IBAction func oneButtonPressed(sender: AnyObject)
{
timesButtonPressed += 1
var buttonTitle1:String! = ("Place ")
var buttonTitle2:String! = ("holder")
if timesButtonPressed == 1
{
buttonTitle1 = sender.titleLabel!?.text
self.answerTyped.text = buttonTitle1
}
if timesButtonPressed == 2
{
buttonTitle2 = sender.titleLabel!?.text
self.answerTyped.text = buttonTitle1 + buttonTitle2
}
}
答案 0 :(得分:1)
问题是当你第二次按下按钮然后是timesButtonPressed == 1,从未执行过,而你的timesButtonPressed == 2如果block从代码中获取title1的值而不是实际的button1标题值。
var timesButtonPressed : NSInteger = 0
var displayString : String = "0"
@IBAction func oneButtonPressed(sender: AnyObject)
{
timesButtonPressed += 1
let buttonTitle:String! = sender.titleLabel!?.text
if timesButtonPressed == 1
{
displayString = buttonTitle
} else {
displayString += buttonTitle
}
self.answerTyped.text = displayString
}
timesButtonPressed var需要根据需要使用(或者在timesButtonPressed = 0时清除显示字符串)
答案 1 :(得分:0)
编辑:
您需要在IBAction函数之外定义两个变量。将以下两个变量放在viewDidLoad()
中var buttonTitle1:String! = ("Place ")
var buttonTitle2:String! = ("holder")
您可以通过重载“+”来替换添加两个字符串:
var str1: String = "Hello"
var str2: String = "World"
var str3: String = str1 + str2
同样,您可以在函数中执行此操作:
self.answerTyped.text = buttonTitle1 + buttonTitle2