如何使用Swift编写随机颜色函数?
import UIKit
class ViewController: UIViewController {
var randomNumber = arc4random_uniform(20)
var randomColor = arc4random()
//Color Background randomly
func colorBackground() {
// TODO: set a random color
view.backgroundColor = UIColor.yellow
}
}
static func random() -> CGFloat
在static func random() -> UIColor
之外是无用的,因此您可以在第二个方法中声明第一个方法。 - Vyachaslav Gerchicovrandom(in:)
函数,用于返回随机值。对于 CGFloat 类型,该函数为static func random(in range: ClosedRange<CGFloat>) -> CGFloat
。因此,您可以只使用.random(in: 0...1)
,无需编写您自己的random()
函数。 - Duncan C