swift實現隨機背景色
本文實例為大傢分享瞭swift實現隨機背景色的具體代碼,供大傢參考,具體內容如下
// // ViewController.swift // 網絡獲取圖片 // // Created by 悅兌科技 on 15/1/27. // Copyright (c) 2015年 BSY. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() [self .addButton()] } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.view.backgroundColor = UIColor.whiteColor() } func addButton() { // 創建button var button:UIButton = UIButton.buttonWithType(UIButtonType.Custom) as UIButton var frame = CGRectMake(100, 100, 100, 100) button.frame = frame // 設置字體 button.setTitle("隨即色", forState: UIControlState.Normal) button.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal) button.titleLabel?.font = UIFont(name: "Heiti SC", size: 20) // 設置圓形 self.view.addSubview(button) button.layer.borderColor = UIColor.lightGrayColor().CGColor button.layer.borderWidth = 2 button.layer.cornerRadius = 50 button.layer.backgroundColor = UIColor.whiteColor().CGColor [button .addTarget(self, action: "buttonClick", forControlEvents: UIControlEvents.TouchUpInside)] } /** button方法實現 */ func buttonClick() { /** * 創建顏色 */ var color = UIColor(red: 183/255.0, green: 183/255.0, blue: 183/255.0, alpha: 1.0) var color1 = UIColor.blueColor() var color2 = UIColor.brownColor() var color3 = UIColor.yellowColor() var color4 = UIColor.orangeColor() var color5 = UIColor.blackColor() /** * 創建可變數組並把顏色添加到數組 */ var arrM :NSMutableArray = NSMutableArray() arrM.addObject(color) arrM.addObject(color1) arrM.addObject(color2) arrM.addObject(color3) arrM.addObject(color4) arrM.addObject(color5) /** * 把顏色賦值給父控件的view */ self.view.backgroundColor = arrM.objectAtIndex(Int(arc4random_uniform(UInt32(arrM.count)))) as? UIColor } }
效果:
以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。