通过按钮生成随机图像

时间:2015-12-31 02:53:58

标签: ios swift image random arc4random

我正在开发一个项目来生成数组中的随机图像。我遇到了一个问题。我将在屏幕名称generage shapes上有一个按钮。一旦用户点击此按钮,generate shapes按钮就会隐藏,4个按钮会显示4种不同的形状。我在使用我的阵列中的图像显示这4个按钮时遇到问题。我尝试了一个switch语句,但它没有通过。我在下面提供了我的代码。

import UIKit

class ShapesDetailViewController: UIViewController {

    var random = arc4random_uniform(4)

    @IBOutlet weak var titleBar: UINavigationItem!

    @IBOutlet weak var displayMessageLabel: UILabel!

    var myImages = [ "diamond.png", "decagon.png", "dodecagon.png", "hectagon.png", "heptagon.png", "octagon.png", "parallelogram.png", "pentagon.png", "rectangle.png", "rightTriangle.png", "square.png", "trapezoid.png", "triangle.png"]

    //my image labels

    @IBOutlet weak var buttonOne: UIButton!
    @IBOutlet weak var buttonTwo: UIButton!
    @IBOutlet weak var buttonThree: UIButton!
    @IBOutlet weak var buttonFour: UIButton!

    @IBOutlet weak var generateImage: UIButton!

    override func viewDidLoad() {

        self.buttonFour.hidden = true
        self.buttonOne.hidden = true
        self.buttonThree.hidden = true
        self.buttonTwo.hidden = true
        displayMessageLabel.hidden = true

    }

    @IBAction func generateRandomImages(sender: AnyObject) {

        displayMessageLabel.hidden = false

        buttonOne.hidden = false

        switch(random){

        case 0: buttonOne.imageView?.image = UIImage(named: "circle.png")
            break

        case 1: buttonOne.imageView?.image = UIImage(named: "decagon.png")
            break

        case 2: buttonOne.imageView!.image = UIImage(named: "diamond.png")
            break

        case 3: buttonOne.imageView!.image = UIImage(named: "hectagon.png")
            break
        default:
            break;

        }

        generateImage.hidden = true
    }
 }

1 个答案:

答案 0 :(得分:1)

我认为问题在于你无法通过其图像视图属性更改按钮的图像,您需要使用图像的setter方法。像这样:

buttonOne.setImage(UIImage(named: "circle"), forState: UIControlState.Normal)