单击 UIAlertController 中的操作时如何更改 UIButton 背景图片?
How do I change a UIButton background picture when an action in a UIAlertController is clicked?
@IBOutlet weak var myPictureOutlet: UIButton!
@IBAction func myPictureAction(_ sender: Any) {
let alert = UIAlertController(title: "Chnage Pic", message: "to Change the pic, press the button below", preferredStyle: . alert)
alert.addAction(UIAlertAction(title: "change picture", style: .default, handler: { (action) in
alert.dismiss(animated: true, completion: nil)
self.myPictureOutlet.setBackgroundImage(ButtonImage, for: UIControlState.normal)
}))
self.present(alert, animated: true, completion: nil)
}
我的目标是:
- 单击
UIButton
(带有默认图片)时创建 UIAlertController
- 然后,当用户单击
UIAlertController
中的按钮时,它会更改 UIButton
图片。
我在完成这项任务时遇到了一些麻烦。当我触摸 UIButton
时 UIAlert
正在工作,但是 UIButton
背景没有改变。请检查我的代码,如果有问题请告诉我。
您的代码应该确实有效。不过你不需要这一行:
alert.dismiss(animated: true, completion: nil)
UIAlertController 会在您按下警报按钮后为您移除它。
另外,为了改进您的代码,只需像这样引用 IBAction 发件人:
guard let button = sender as? UIButton else {
print("Ooops, not a button!")
return
}
button.setBackgroundImage(ButtonImage, for: UIControlState.normal)
@IBOutlet weak var myPictureOutlet: UIButton!
@IBAction func myPictureAction(_ sender: Any) {
let alert = UIAlertController(title: "Chnage Pic", message: "to Change the pic, press the button below", preferredStyle: . alert)
alert.addAction(UIAlertAction(title: "change picture", style: .default, handler: { (action) in
alert.dismiss(animated: true, completion: nil)
self.myPictureOutlet.setBackgroundImage(ButtonImage, for: UIControlState.normal)
}))
self.present(alert, animated: true, completion: nil)
}
我的目标是:
- 单击
UIButton
(带有默认图片)时创建UIAlertController
- 然后,当用户单击
UIAlertController
中的按钮时,它会更改UIButton
图片。
我在完成这项任务时遇到了一些麻烦。当我触摸 UIButton
时 UIAlert
正在工作,但是 UIButton
背景没有改变。请检查我的代码,如果有问题请告诉我。
您的代码应该确实有效。不过你不需要这一行:
alert.dismiss(animated: true, completion: nil)
UIAlertController 会在您按下警报按钮后为您移除它。
另外,为了改进您的代码,只需像这样引用 IBAction 发件人:
guard let button = sender as? UIButton else {
print("Ooops, not a button!")
return
}
button.setBackgroundImage(ButtonImage, for: UIControlState.normal)