我想通过从图像数组中选择一个随机值来更改显示的图像。
import UIKit
class ViewController: UIViewController {
let imageArray = ["ball1", "ball2", "ball3", "ball4", "ball5"]
var number: Int = 0
@IBOutlet weak var myImage: UIButton!
@IBAction func buttonPressed(_ sender: UIButton) {
number = Int.random(in: 0 ... 4)
myImage.image = UIImage(named: imageArray[number+1])
}
override func viewDidLoad() {
super.viewDidLoad()
myImage.image = UIImage(named: "ball1")
number = Int.random(in: 0 ... 4)
myImage.image = UIImage(named: imageArray[number+1])
}
}
在第19、24和26行(无论何时尝试更改图像),都会出现错误“无法分配给值:'image is a method'”。为什么会这样?
答案 0 :(得分:0)
使用image
属性设置state
等于.normal
:
import UIKit
class ViewController: UIViewController {
let imageArray = ["ball1", "ball2", "ball3", "ball4", "ball5"]
var number: Int = 0
@IBOutlet weak var myImage: UIButton!
@IBAction func buttonPressed(_ sender: UIButton) {
number = Int.random(in: 0 ... 4)
myImage.setImage(UIImage(named: imageArray[number+1]), for: .normal)
}
override func viewDidLoad() {
super.viewDidLoad()
myImage.setImage(UIImage(named: "ball1"), for: .normal)
number = Int.random(in: 0 ... 4)
myImage.setImage(UIImage(named: imageArray[number+1]), for: .normal)
}
}