简体   繁体   English

将生成随机背景颜色的按钮 - Xcode - Swift

[英]Button that will generate a random background color - Xcode - Swift

I'm trying to make a button that will change the background color to a random color.我正在尝试制作一个将背景颜色更改为随机颜色的按钮。 So far I have:到目前为止,我有:

func randomCGFloat() -> CGFloat {
return CGFloat(arc4random()) / CGFloat(UInt32.max)}

extension UIColor {
    static func randomColor() -> UIColor {
        let r = randomCGFloat()
        let g = randomCGFloat()
        let b = randomCGFloat()

        // If you wanted a random alpha, just create another
        // random number for that too.
        return UIColor(red: r, green: g, blue: b, alpha: 1.0)
    }
}

All of this goes outside the view controller because 'extension' is not allowed inside the view controller and must be at file scope.所有这些都在视图控制器之外,因为视图控制器内部不允许“扩展”,并且必须在文件范围内。

Then I have this inside the view controller:然后我在视图控制器中有这个:

 override func viewDidLoad() {
    super.viewDidLoad()
    self.view.backgroundColor = UIColor.randomColor()

For my action button:对于我的操作按钮:

@IBAction func changeColor(sender: UIButton) {}

So far the app boots up with a random color.到目前为止,应用程序以随机​​颜色启动。 I don't know how to make the action button change the background color to a new random color because background color is outside the scope of my action.我不知道如何让操作按钮将背景颜色更改为新的随机颜色,因为背景颜色超出了我的操作范围。 I can't put the action outside of the view controller class.我不能把动作放在视图控制器类之外。 The button has to generate a new random color and update the background color.该按钮必须生成新的随机颜色并更新背景颜色。

As long as changeColor is in your view controller, you can just do只要changeColor在你的视图控制器中,你就可以做

@IBAction func changeColor(sender: UIButton) {
    self.view.backgroundColor = UIColor.randomColor()
}

and then you have to connect a touch event of your button (say, touchUpInside) to the action.然后您必须将按钮的触摸事件(例如,touchUpInside)连接到操作。 You can do that in Interface Builder (easy) or in code (trickier, but equally easy when you get the hang of it).您可以在 Interface Builder(简单)或代码(更棘手,但当您掌握它时同样容易)中做到这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM