I want to change the background image on the next page by pressing the button, but it doesn't work.

Asked 2 years ago, Updated 2 years ago, 86 views

<Error Occurring>
You can do it, but if you press the first button,
An error similar to the following appears in the part where getimage.image=bin1 is written:

Unexpectedly found nil while unwrapping an Optional value

<Supplement>
Buttons are tagged.

Code

import UIKit

classViewController:UIViewController, UIActionSheetDelegate{


    @IBOutlet weak var getimage:UIImageView!

    // Image file definition ~ changed name to bin (number)
    var bin1 = UIImage(named: "binsen1.jpg")!
    var bin2 = UIImage(named: "binsen2.jpg")!
    var bin3 = UIImage(named: "binsen3.png")!


    @ IBAction function(_sender:UIButton){
        switch sender.tag {
        case1:
        Display image in UIImage called // getimage
            getimage.image=bin1
        case2:
            getimage.image=bin2
        case3:
            getimage.image=bin3

        default —break
        }
    }

    override func viewDidLoad(){
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from anib.
    }

    override funcdidReceiveMemoryWarning(){
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

swift4

2022-09-30 10:46

1 Answers

Does it work as expected only when I press the second and third buttons?

If you get the same error when you press the second or third button,
Verify that files from binsen1.jpg to binsen3.jpg have been added to the project and that the Build PhaseCopy Bundle Resources contains the above files.

By the way, there is no need to actively fix it, but there are about two things that are better to fix.

  • bin1~bin3 should be let if you do not want to reprint UIImage
  • The declaration of
  • variable should be followed by :type/class name after the variable name, and I think it is better to write down the type exactly what you want to store in the variable you declared now

It looks like the following.

let bin1: UIImage=UIImage(named: "binsen1.jpg")!
let bin2: UIImage = UIImage (named: "binsen2.jpg")!
let bin3: UIImage = UIImage(named: "binsen3.jpg")!


2022-09-30 10:46

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.