带按钮的圆形 UIView 以随机化它的颜色

Circle UIView with button to randomize it color

我正在学习 UIView,但遇到了问题。

我有一个圆形的 UIView,我使用以下方法创建它:

import UIKit

    class Ball: UIView {

        override func drawRect(rect: CGRect) {
            var path = UIBezierPath(ovalInRect: rect)
            var randColor: UIColor = Colors.randomColor()
            randColor.setFill()

            Colors.ballColor = randColor
            Colors.colorPosition = find(Colors.arrayColors, randColor)!
            println("Randomizando -> \(Colors.colorPosition)")

            path.fill()
        }
    }

我有一个按钮,我调用 setNeedDisplay 将其颜色随机化,但 drawRect 函数被调用了两次。

随机函数:

 func randomize(){
    ball.setNeedsDisplay()
 } 

球是出口:

@IBOutlet weak var ball: Ball!




Color class:

class Colors {

    static var arrayColors = [
        UIColor.blackColor(),
        UIColor.whiteColor(),
        UIColor.grayColor(),
        UIColor.redColor(),
        UIColor.greenColor(),
        UIColor.blueColor(),
        UIColor.yellowColor(),
        UIColor.orangeColor(),
        UIColor.purpleColor(),
        UIColor.brownColor()]

    static let arrayColorsNames = [
        "Preto",
        "Branco",
        "Cinza",
        "Vermelho",
        "Verde",
        "Azul",
        "Amarelo",
        "Laranja",
        "Roxo",
        "Marrom"]


    static var ballColor: UIColor = UIColor.whiteColor()
    static var colorPosition: Int = -1

    static func randomColor() -> UIColor{

        if let randomColor = Int(arc4random_uniform(UInt32(arrayColors.count))) as? Int{
            return arrayColors[randomColor]
        }

        return UIColor.blueColor()
    }

    static func randomColorName() -> String{

        if let randomColorName = Int(arc4random_uniform(UInt32(arrayColorsNames.count))) as? Int{
            return arrayColorsNames[randomColorName]
        }

        return "Azul"
    }

}

按钮操作:

@IBAction func colorButtonClicked(sender: UIButton) {
    if sender.titleLabel?.text == Colors.arrayColorsNames[Colors.colorPosition]{
        println("IGUAIS")
    }
    randomize()
}

问题是:drawRect函数被调用了两次,颜色改变了2次

用这个替换随机函数。

func randomize(){
    ball.backgroundColor = randomColor()
 }