RGB調色盤:view + slider * 3 + textfield * 3
昨天介紹了每個物件的功能!
今天主要講解:
除了講解程式碼之外,還會附上截圖以供參考。
extension ViewController : UITextFieldDelegate {
//新的字串可判斷字串長度,決定是否可以輸入。回傳 true 允許文字輸入,回傳 false 讓文字不能輸入。
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
var result = false
if let text = textField.text, let range = Range(range, in: text) {
let newText = text.replacingCharacters(in: range, with: string)
// 判斷只能輸入3位數
if newText.count < 4 {
result = true
}
}
return result
}
}
在 storyboard 拉線到對應的 @IBAction
textField:
slider:
delegate:
附上RGB調色盤完整程式碼
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var showcolor: UIView!
@IBOutlet weak var redtext: UITextField!
@IBOutlet weak var greentext: UITextField!
@IBOutlet weak var bluetext: UITextField!
@IBOutlet weak var redslider: UISlider!
@IBOutlet weak var greenslider: UISlider!
@IBOutlet weak var blueslider: UISlider!
override func viewDidLoad() {
super.viewDidLoad()
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyBoard))
self.view.addGestureRecognizer(tap)
}
@objc func dismissKeyBoard() {
self.view.endEditing(true)
}
@IBAction func TextFieldToSilder(textField: UITextField) {
guard let stringColor = textField.text else {return}
guard let intColor = Int(stringColor)else {return}
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
}
}
@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)
}
}
extension ViewController : UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
var result = false
if let text = textField.text, let range = Range(range, in: text) {
let newText = text.replacingCharacters(in: range, with: string)
if newText.count < 4 {
result = true
}
}
return result
}
}
明天會介紹關於 storyboard 的 layout(約束)拉法,敬請期待!