我已经在这个问题上阅读了几个答案,但似乎找不到适用于我的代码的答案。当我分配"文本" " myLabel" (下面)我得到:" [UIButton setText:]:无法识别的选择器发送到实例...."程序编译好,但遇到赋值语句时崩溃。
但是我能够分配甚至打印出同一对象的backgroundColor。关于我做错了什么想法?
// ******** 导入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.
}
}
答案 0 :(得分:3)
您似乎已将UIButton
(位于故事板或xib上)与代码中的UILabel
相关联,并且您正尝试将其视为标签。确保将IB上的按钮更换为标签,它将起作用。
答案 1 :(得分:0)
不要传递局部变量
3
现在如果你想设置按钮的标题
func makeColor()
{
myLabel.backgroundColor = UIColor(red: 0.1, green: 0, blue: 0, alpha: 0.1)
print(myLabel.backgroundColor)
myLabel.text = "4"
}
@IBAction func myButton(sender: AnyObject) {
makeColor ()
}
答案 2 :(得分:0)
尝试在不知道来源(xib ||故事板)的情况下缓解此错误
extension UIButton
{
func setText(_ text: String) {
assertionFailure("crashlytics reported Fatal Exception: NSInvalidArgumentException -[UIButton setText:]: unrecognized selector sent to instance 0xyyy objc_exception_throw keyboard_arrow_down")
titleLabel?.text = text
}
}