我试着做一个按钮,将背景颜色更改为随机颜色。到目前为止,我已经:
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)
}
}所有这些都在视图控制器之外,因为在视图控制器中不允许“扩展名”,并且必须位于文件范围内。
然后,在视图控制器中有这样的内容:
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.randomColor()我的动作按钮:
@IBAction func changeColor(sender: UIButton) {}到目前为止,该应用程序以随机颜色启动。我不知道如何使动作按钮将背景颜色更改为新的随机颜色,因为背景色不在我的操作范围之内。我不能将操作放在视图控制器类之外。该按钮必须生成新的随机颜色并更新背景色。
发布于 2015-11-23 22:48:05
只要changeColor在您的视图控制器中,您就可以这样做。
@IBAction func changeColor(sender: UIButton) {
self.view.backgroundColor = UIColor.randomColor()
}然后,您必须将按钮的触摸事件(例如,touchUpInside)连接到操作。您可以在Interface (轻松)或代码(更复杂,但同样容易,当您掌握它的窍门)中做到这一点。
https://stackoverflow.com/questions/33882130
复制相似问题