【发布时间】:2016-11-01 08:29:01
【问题描述】:
我有一个应该显示分数的标签,以及一个应该在每次按下时增加分数的按钮。我的问题是无论我把函数放在哪里都会出错。
如果我有 viewDidLoad 类之上的函数,那么我会收到一个错误,因为它出现在我的标签之前,但是如果我将它放在 viewDidLoad 内的任何位置,我会收到一个错误,因为我无法调用本地函数,如果我把它之后的任何地方,然后我调用该函数的按钮位于该函数之前。
我应该把这些东西放在哪里?有没有更好的方法一起做这一切?这本该如此简单……
import UIKit
class ViewController: UIViewController {
let phrase = "Your score: "
var increasingNum = 0
func scoreGoUp (sender: UIButton){
increasingNum += 1
label.text = "\(phrase) \(increasingNum)"
}
override func viewDidLoad() {
super.viewDidLoad()
let label = UILabel(frame: CGRect(x: self.view.frame.size.width / 2 - 100, y: self.view.frame.size.height / 2 - 10, width: 200, height: 20))
label.textAlignment = .center
label.text = "\(phrase) \(increasingNum)"
self.view.addSubview(label)
let button = UIButton(frame: CGRect(x: self.view.frame.size.width / 2 - 150, y: 100, width: 300, height: 50))
button.backgroundColor = UIColor.cyan
button.addTarget(self, action: #selector(scoreGoUp), for: .touchUpInside)
self.view.addSubview(button)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
【问题讨论】:
标签: ios iphone swift xcode swift3