RGB調色盤:view + slider * 3 + textfield * 3
昨天介紹了如何拉物件,今天來教各位如何寫出每個物件的功能!
今天主要講解:
除了講解程式碼之外,還會附上截圖以供參考。
// 按空白處收回鍵盤
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyBoard))
// to Replace "TouchesBegan"
self.view.addGestureRecognizer(tap)
在 override func viewDidLoad() 外新增鍵盤收起的 @objc
// 按空白處收回鍵盤
@objc func dismissKeyBoard() { self.view.endEditing(true) }
// textField 改變 slider
@IBAction func TextFieldToSilder(textField: UITextField) {
// 用 guard let 判斷 textField.text 是否為空值,若有值則stringColor = textField.text;反之,跳出迴圈不會往下執行
guard let stringColor = textField.text else {return}
// 將 stringColor 得到的值轉換成 Int 型態
guard let intColor = Int(stringColor)else {return}
// 用 switch case 去判斷我是在哪個 textField 輸入值
switch textField {
case redtext:
redslider.setValue(Float(intColor), animated: true)
case greentext:
greenslider.setValue(Float(intColor), animated: true)
case bluetext:
blueslider.setValue(Float(intColor), animated: true)
default: break
}
}
// slider 改變 textField
@IBAction func SliderToTextField(_ sender: Any) {
redtext.text = "\(Int(redslider.value))"
greentext.text = "\(Int(greenslider.value))"
bluetext.text = "\(Int(blueslider.value))"
}
// 顯示顏色
@IBAction func colorchange(_ sender: Any){
showcolor.backgroundColor = UIColor(red: CGFloat(redslider.value)/255, green: CGFloat(greenslider.value)/255, blue: CGFloat(blueslider.value)/255, alpha: 1)
}
明天會介紹:
敬請期待!