[英]Change background image with button click
我可以这样在viewDidLoad函数上更改背景图片:
let myBackgroundImage = UIImageView (frame: UIScreen.main.bounds)
myBackgroundImage.image = UIImage(named: "wallpaper-1-iphone-8-plus.png")
myBackgroundImage.contentMode = UIViewContentMode.scaleAspectFill
self.view.insertSubview(myBackgroundImage, at: 0)
我想通过按钮单击执行相同的操作,如下所示:
@IBAction func flip4btn5(_ sender: Any)
{
let myBackgroundImage = UIImageView (frame: UIScreen.main.bounds)
myBackgroundImage.image = UIImage(named: "wallpaper-2-iphone-8-plus.png")
myBackgroundImage.contentMode = UIViewContentMode.scaleAspectFill
self.view.insertSubview(myBackgroundImage, at: 0)
}
但它不会更改背景图片。 为什么呢 你怎么看 ?
我正在使用Swift 4.1。
不要创建新图像。 只需像这样在按钮操作中更改第一个UIImage的图片即可:
myBackgroundImage.image = UIImage(named: "wallpaper-2-iphone-8-plus.png")
每次要更改背景图像时,不要一直添加UIImageViews。
将UIImageView放在需要的视图层次结构中,并保留对其的引用。 然后根据需要在其上设置image属性。
class ViewController: UIViewController {
@IBOutlet weak var backgroundImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
backgroundImageView.image = UIImage(named: "wallpaper-1-iphone-8-plus.png")
}
@IBAction func flip4btn5(_ sender: Any) {
backgroundImageView.image = UIImage(named: "wallpaper-2-iphone-8-plus.png")
}
}
您可以在情节提要中或在viewDidLoad中设置contentMode。 更新图像后,无需保持设置。
let myBackgroundImage = UIImageView (frame: CGRect.zero)
override func viewDidLoad() {
super.viewDidLoad()
myBackgroundImage.image = UIImage(named: "wallpaper-1-iphone-8-plus.png")
myBackgroundImage.contentMode = UIViewContentMode.scaleAspectFill
self.view.addSubview(myBackgroundImage)
}
@IBAction func ButtonPressed(_ sender: Any) {
myBackgroundImage.image = UIImage(named: "wallpaper-2-iphone-8-plus.png")
}
试试这个代码,它工作正常。
class ViewController: UIViewController {
var myBackgroundImage = UIImageView (frame: UIScreen.main.bounds);
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
myBackgroundImage.image = UIImage(named: "wallpaper-1-iphone-8-plus.png")
myBackgroundImage.contentMode = UIViewContentMode.scaleAspectFill
self.view.insertSubview(myBackgroundImage, at: 0)
}
@IBAction func flip4btn5(_ sender: UIButton) {
myBackgroundImage.image = UIImage(named: "wallpaper-2-iphone-8-plus.png")
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.