简体   繁体   中英

Button Coming From Bottom After Pressing

I'm making an extremely simple iOS app. I press a button and the image changes. The problem I'm running into is every time I press the button, it's like the button goes to the bottom of the phone simulator and lays on top of the button I originally pressed.

Also the image only stays for a split second before disappearing. (I'm assuming these actions go hand in hand).

Here is the code if anyone is able to help.

import UIKit

class ViewController: UIViewController {
    @IBAction func generateHero(_ sender: UIButton) {
        //list of Images in array
        let image : NSArray = [ UIImage(named: "batman.jpg")!,
                                UIImage(named: "the-flash.jpg")!,
                                UIImage(named: "Deadpool.jpg")!,
                                UIImage(named: "green-arrow.jpg")!,
                                UIImage(named: "iron-man.jpg")!]

        //random image generating method
        let imagerange: UInt32 = UInt32(image.count)
        let randomimage = Int(arc4random_uniform(imagerange))
        let generatedimage: AnyObject = image.object(at: randomimage) as AnyObject
        self.heroImage.image = generatedimage as? UIImage
    }

    @IBOutlet weak var heroImage: UIImageView!
}

You are doing a lot of unnecessary conversions in random image generation, if you have used Array instead of NSArray you could use .randomElement() function that returns random element of array. So you would just do self.heroImage.image = image.randomElement()

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