目前,我正在通过以下操作更改图像视图:
@IBOutlet var bgImage: UIImageView!
在情节提要中创建连接的UIimage视图 和
var counter = 0
@IBAction func ChangePic(){
//print(counter)
if(counter == 15){
counter = 0
}
let image: UIImage = UIImage(named: String(counter))!
bgImage = UIImageView(image: image)
bgImage.image = UIImage(named: String(counter))
self.view.addSubview(bgImage!)
counter = counter + 1
}
在此处修改图像视图,此功能连接到情节提要中的按钮,因此单击该按钮可更改图像。出现计数器的原因是因为照片是从0到14枚举的,所以我可以轻松地显示它们。这样效果很好,但是图像会自动调整大小并不断出现在彼此之上
答案 0 :(得分:2)
由于您已经拥有imageView bgImage,因此您要做的就是在bgImage上设置image属性。您不需要每次都创建一个新的imageView。
@IBAction func ChangePic(){
if(counter == 15){
counter = 0
}
bgImage.image = UIImage(named: String(counter))
counter = counter + 1
}
答案 1 :(得分:0)
如果您只想更改图像,则只需执行以下操作:
@IBAction func ChangePic(){
//print(counter)
if(counter == 15){
counter = 0
}
bgImage.image = UIImage(named: String(counter))
counter = counter + 1
}
您当前的代码:
@IBAction func ChangePic(){
//print(counter)
if(counter == 15){
counter = 0
}
// You create new image
let image: UIImage = UIImage(named: String(counter))!
// You set new instance to your imageView with your updated image (No need to do this because the object is not nil)
bgImage = UIImageView(image: image)
// You set again your updated image (only this line required )
bgImage.image = UIImage(named: String(counter))
// No needed
self.view.addSubview(bgImage!)
counter = counter + 1
}