用按钮单击更改背景图像

时间:2018-04-17 10:53:05

标签: ios swift uiimageview

我可以像这样更改viewDidLoad func上的背景图片:

    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。

4 个答案:

答案 0 :(得分:1)

不要创建新图片。只需在按钮操作中更改第一个UIImage的图片,如下所示:

myBackgroundImage.image = UIImage(named: "wallpaper-2-iphone-8-plus.png")

答案 1 :(得分:0)

每次要更改背景图像时,都不要继续添加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")
   }
}

您可以在storyboard或viewDidLoad中设置contentMode。更新图像后无需继续设置。

答案 2 :(得分:0)

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")

}

答案 3 :(得分:0)

试试这段代码,它工作正常。

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")    
    }    
}
相关问题