【发布时间】:2016-02-27 11:43:38
【问题描述】:
我已阅读有关此问题的多个答案,但似乎找不到适用于我的代码的答案。当我分配“myLabel”的“text”成员(如下)时,我得到:“[UIButton setText:]: unrecognized selector sent to instance....”程序编译正常,但遇到赋值语句时崩溃。
但是我能够分配甚至打印出同一对象的背景颜色。关于我做错了什么有什么想法吗?
//******** 导入 UIKit
class ViewController: UIViewController {
//********* Button 1 *********//
@IBOutlet weak var lbl1: UILabel!
@IBAction func btn1(sender: AnyObject) {
nextColorFor1++
makeColor (self.lbl1, nextColor: nextColor1)
}
//**** Button 2 **********//
@IBOutlet weak var lbl2: UILabel!
@IBAction func btn2(sender: AnyObject) {
nextColorFor2++
makeColor (self.lbl2, nextColor: nextColorFor2)
}
//***************************//
func makeColor (myLabel:UILabel, nextColor:Int)
{
switch nextColor
{
case 0: myLabel.backgroundColor = UIColor(red: 0.1, green: 0, blue: 0, alpha: 0.1)
case 1: myLabel.backgroundColor = UIColor(red: 0.2, green: 0, blue: 0, alpha: 0.2)
case 2: myLabel.backgroundColor = UIColor(red: 0.3, green: 0, blue: 0, alpha: 0.3)
case 3: myLabel.backgroundColor = UIColor(red: 0.4, green: 0, blue: 0, alpha: 0.4)
case 4: myLabel.backgroundColor = UIColor(red: 0.5, green: 0, blue: 0, alpha: 0.5)
default: print("end of colors")
}
print(myLabel.backgroundColor)
myLabel.text = "4" <<< --- This is where the crask occurs
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
}
【问题讨论】:
-
还有一件事——按钮和标签都连在一起了。
-
为避免混淆,请勿使用相同的名称,例如实例和局部变量 (
myLabel)。 -
按钮和标签连在一起是什么意思?
-
有什么理由不赞成我的回答吗?我试过了,我放在这里。
-
对不起各位。我认为当我试图简化示例时,我失去了对我正在尝试做的事情的一些解释,随后在您的一些回答中造成了混乱。对于那个很抱歉。我修改了代码以表明我必须将标签的多种可能性发送到函数。此外,每个对象都由一个标签和一个按钮指向。 (ps user3182143 - 不是我拒绝了你的答案)