使用按钮圈出UIView以随机化它的颜色

时间:2015-07-26 14:03:22

标签: swift uiview ios8

我正在学习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:

 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倍

1 个答案:

答案 0 :(得分:1)

用此替换randomize函数。

public class Test {
    public static void main(String[] args) throws java.lang.Exception {
        NavigationTree<DrawerListItem<Screen>> nt = new NavigationTree<>();
        nt.insert(new DrawerListItem<Screen>(), new DrawerListItem<Screen>());
    }

    private static class NavigationTree<T extends BaseListItem<? extends BaseData>> {
        public boolean insert(final T parent, final T child) {
            return true;
        }
    }

    private static class DrawerListItem<T> extends BaseListItem<T> {}
    private static class BaseListItem<T> {}
    private static class Screen extends BaseData {}
    private static class BaseData {}
}