我正在研究 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/