为 Swift 3 更新
lazy var toggleBT: UIButton = {
let button = UIButton()
button.frame = CGRect(x: 40, y: 100, width: 200, height: 40)
button.backgroundColor = .orange
button.isSelected = false // optional(because by default sender.isSelected is false)
button.setTitle("OFF", for: .normal)
button.setTitleColor(.white, for: .normal)
button.titleLabel?.font = .boldSystemFont(ofSize: 14)
button.addTarget(self, action: #selector(handleToggleBT), for: .touchUpInside)
return button
}()
func handleToggleBT(sender: UIButton) {
sender.isSelected = !sender.isSelected
if sender.isSelected {
print(sender.isSelected)
toggleBT.setTitle("ON", for: .normal)
}
else {
print(sender.isSelected)
toggleBT.setTitle("OFF", for: .normal)
}
} // don't forget to add this button as a subView for eg. view.addSubview(toggleBT)