如何在 swift 中的 anyObject 按钮中禁用按钮
How to disable a button within a anyObject Button in swift
好的,所以我希望能够禁用其自身的按钮。所以当我按下按钮时,它会自行禁用。
import UIKit
class ViewController: UIViewController {
@IBOutlet var buttons: [UIButton]!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func but(_ sender: AnyObject) {
//this code doesn't seem to work at all, and I don't know why
(sender as AnyObject).isEnabled = false
}
}
每当我尝试执行此操作时,它都会给我一条错误消息“无法分配给‘@lvalue Bool 类型的不可变表达式?’”
那么有没有其他方法可以禁用此按钮
据推测,您已经在 Interface Builder 中将此 IBAction
连接到 UIButton
。因此,您可以将函数签名更改为:
@IBAction func but(_ sender: UIButton) {
sender.isEnabled = false
}
AnyObject
没有名为 isEnabled
的 属性,这就是您之前的代码失败的原因。
在我使用此代码的按钮中
@IBAction func but(_ sender: AnyObject) {
var disableMyButton = sender as? UIButton
disableMyButton?.isEnabled = false
}
好的,所以我希望能够禁用其自身的按钮。所以当我按下按钮时,它会自行禁用。
import UIKit
class ViewController: UIViewController {
@IBOutlet var buttons: [UIButton]!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func but(_ sender: AnyObject) {
//this code doesn't seem to work at all, and I don't know why
(sender as AnyObject).isEnabled = false
}
}
每当我尝试执行此操作时,它都会给我一条错误消息“无法分配给‘@lvalue Bool 类型的不可变表达式?’”
那么有没有其他方法可以禁用此按钮
据推测,您已经在 Interface Builder 中将此 IBAction
连接到 UIButton
。因此,您可以将函数签名更改为:
@IBAction func but(_ sender: UIButton) {
sender.isEnabled = false
}
AnyObject
没有名为 isEnabled
的 属性,这就是您之前的代码失败的原因。
在我使用此代码的按钮中
@IBAction func but(_ sender: AnyObject) {
var disableMyButton = sender as? UIButton
disableMyButton?.isEnabled = false
}