Light App的應用
Published in
4 min readAug 1, 2018
學習目的
-練習 IBOutlet 和 IBAction
-利用 UIColor 物件,UIImage 物件和亂數
當進入App會隨機選一種顏色或是貼圖,之後點擊按照順序切換畫面,圖片我選用美食圖,聽說黃色會刺激一些食慾不知道是不是真的?
1.以第一張Gif圖為基礎,首先產生各種顏色物件
(參考:https://www.webnots.com/vibgyor-rainbow-color-codes/)
let violet = UIColor(red: 148/255, green: 0, blue: 211/255, alpha: 1)let indigo = UIColor(red: 75/255, green: 0, blue: 130/255, alpha: 1)let blue = UIColor(red: 0, green: 0, blue: 1, alpha: 1)let green = UIColor(red: 0, green: 1, blue: 0, alpha: 1)let yellow = UIColor(red: 1, green: 1, blue: 0, alpha: 1)let orange = UIColor(red: 1, green: 127/255, blue: 0, alpha: 1)let red = UIColor(red: 1, green: 0, blue: 0, alpha: 1)
2.接下來準備一個放顏色的陣列跟一個產生亂數的常數等下用
var rainbow : [UIColor] = [UIColor]()var colorNumber = Int.random(in: 0...6)
3.在viewDidLoad()將我們剛生成的顏色放進去
override func viewDidLoad() {super.viewDidLoad() rainbow = [violet,indigo,blue,green,yellow,orange,red] //當進入畫面設置一個顏色
view.backgroundColor = rainbow[colorNumber]}
4.接下來準備點擊畫面的action,可以使用Button,我是使用TapGestureRecognizer這個元件一樣可以
@IBAction func colorChange(_ sender: Any) { view.backgroundColor = rainbow[colorNumber] if colorNumber == 6 { colorNumber = 0 } else { colorNumber += 1 }}
這樣就完成進入畫面隨機一種顏色並且點擊切換7彩的顏色了
彩虹切換GitHub:
接下來是第二張Gif圖的圖片切換,與第一張Gif異曲同工之妙
1.放圖進去Assets,並且生成圖片名稱的陣列還有隨機亂數
let imageName = ["咖喱飯","蝦仁飯加蛋","魚羹飯","拌飯","麻辣鍋燒意麵"]var imageNumber = Int.random(in: 0...4)
2.這裡要拉一個imageView的outlet來使用,並且再拉一個action來切換這個imageView的outlet
@IBOutlet weak var imageView: UIImageView!@IBAction func imageChangeClick(_ sender: UITapGestureRecognizer) { ...}
3.在action裡面寫上要切換圖片的程式碼
@IBOutlet weak var imageView: UIImageView!@IBAction func imageChangeClick(_ sender: UITapGestureRecognizer) { imageView.image = UIImage(named: imageName[imageNumber]) if imageNumber == 4{ imageNumber = 0 } else { imageNumber += 1 }}
兩邊其實差別不大只要了解需要的物件還有action如何使用便可完成
美食圖切換GitHub: