简体   繁体   中英

Display images instead of colours when in Beacon range

I am trying to program an app to change screens when it enters the range of a beacon and have been following this tutorial: https://www.hackingwithswift.com/example-code/location/how-to-detect-ibeacons

The tutorial uses the code:

func updateDistance(_ distance: CLProximity) {
UIView.animate(withDuration: 0.8) {
    switch distance {
    case .unknown:
        self.view.backgroundColor = UIColor.gray

    case .far:
        self.view.backgroundColor = UIColor.blue

    case .near:
        self.view.backgroundColor = UIColor.orange

    case .immediate:
        self.view.backgroundColor = UIColor.red

to tell the app to change to different colours depending on how far the beacon is in relation to the device. I would like my app to do the same thing however instead of displaying colours I would like it to display images.

I have tried using the UIImageView but it does not provide me with the option to select an image similar to how it lets me select a colour when using UIColor

Can someone explain to me how to make it display images instead of colours?

I am using Xcode 8.3.2

Ok, you need to take several steps:

Go into interface Builder and create an image view. Set up layout constraints to place it where you want on the screen, and constraints to set its height and width to the height and width of the images you want to display.

Now open an assistant editor window and set it to "automatic", which should cause it to display the source for your view controller.

Control-drag from your image view into the top of your view controller to create an IBOutlet. Let's call it anImageView .

Create images in your app's asset catalog at the target resolutions you want to support. You probably want @2x and @3x sized images for retina devices and for the 6+. You don't need non-retina images any more since iOS 9 and later doesn't support non-retina devices any more.

Lets say you have entries in your asset catalog called "unknown.png", "far.png", "near.png" and "immediate.png" that are all the same dimensions (say 100x100 points with @2x and @3x versions, just for example.)

Now rewrite your function like this:

func updateDistance(_ distance: CLProximity) {
    switch distance {
    case .unknown:
        anImageView.image = UIImage(named: "unknown")

    case .far:
        anImageView.image = UIImage(named: "far")

    case .near:
        anImageView.image = UIImage(named: "unknown")

    case .immediate:
        anImageView.image = UIImage(named: "immediate")
}

That should do it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM