swift - 用按钮圈住 UIView 以使其颜色随机化

标签 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 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()
 }

关于swift - 用按钮圈住 UIView 以使其颜色随机化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31637839/

相关文章:

ios - 如何为倒数计时器创建循环进度指示器

ios - 在 iOS 运行时更改 subview

ios - 响应 child 和 parent 的触摸事件

ios - 初始化时 Swift 额外参数

swift - 为什么我的自定义 UICollectionViewLayout 在单元格之间添加空间时会抛出错误?

ios - 引用 UICollectionView header 补充 View 的更简洁、更不脆弱的方式

ios - popViewController 操作后的上边距 UITableViewController

swift - 无法通过 ID 找到约束

javascript - iOS 8 Beta 2 中的 Cordova 地理定位问题

ios - Apple 二进制文件被拒绝 (2.16)