練習二.用程式畫國旗(法國)

step1.

設定一個座標為(0.0)寬度600高度300框框

var rect = CGRect(x: 0, y: 0, width: 600, height: 300)

step2.

產生一個型別 UIView 的東西存到常數 rectview 裡

let rectview = UIView(frame: rect)

step3.

將rectview的背景顏色設為藍色並作為底圖

rectview.backgroundColor = UIColor(red: 3/255, green: 40/255, blue: 142/255, alpha: 1)

*小提示alpha需設為1 不透明 若為0則看不到顏色

step4.

依上步驟陸續產出白色以及紅色框框

rect = CGRect(x: 200, y: 0, width: 200, height: 300)let whiteview = UIView(frame: rect)whiteview.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 1)

/////////////////////////////////////////////////////////////////////

rect = CGRect(x: 400, y: 0, width: 200, height: 300)let redview = UIView(frame: rect)redview.backgroundColor = UIColor(red: 219/255, green: 63/255, blue: 65/255, alpha: 1)

*座標的部分(0,0)為最左上角,越往右X越大,越往下Y越大。

step5.

最後用上課所教的addSubview方法將紅、白兩框框加入

rectview.addSubview(whiteview)rectview.addSubview(redview)

以下完整程式碼:

import UIKitvar rect = CGRect(x: 0, y: 0, width: 600, height: 300)let rectview = UIView(frame: rect)rectview.backgroundColor = UIColor(red: 3/255, green: 40/255, blue: 142/255, alpha: 1)rect = CGRect(x: 200, y: 0, width: 200, height: 300)let whiteview = UIView(frame: rect)whiteview.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 1)rect = CGRect(x: 400, y: 0, width: 200, height: 300)let redview = UIView(frame: rect)redview.backgroundColor = UIColor(red: 219/255, green: 63/255, blue: 65/255, alpha: 1)rectview.addSubview(whiteview)rectview.addSubview(redview)

剛開始弄懂觀念花了些時間 (⊙0⊙”)A

練習做了幾次才覺得很簡單

--

--