概要
フォーカス時に背景色が変わるUITextFieldを作ってみました。
背景色はストーリーボードで指定できるようにしています。
動作イメージ
開発環境
Xcode7.3
コード
1. UITextField拡張クラスの作成
UITextFieldを継承したクラスを作成します。
UITextFieldCustom.swift
import UIKit
@IBDesignable
class UITextFieldCustom: UITextField, UITextFieldDelegate {
@IBInspectable var focusBkColor: UIColor?
private var defaultBkColor: UIColor?
func textFieldDidBeginEditing(textField: UITextField) {
if focusBkColor == nil {
print("Error: Set focusBkColor")
return
}
defaultBkColor = self.backgroundColor
self.backgroundColor = focusBkColor
}
func textFieldDidEndEditing(textField: UITextField) {
self.backgroundColor = defaultBkColor
}
}
2. ストーリーボード
UITextFieldを配置し、Identity InspectorのClassに上記UITextField拡張クラスを指定します。
UITextField拡張クラスのコードに@IBInspectable var focusBkColor: UIColor?
の記述をすることで、Attribute InspectorにFocus Bk Colorというプロパティが出現します。
このプロパティにて、フォーカス時の背景色を指定できるようにしてみました。
3. ViewController
ViewController.swift
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var textFieldCustom1: UITextFieldCustom!
@IBOutlet weak var textFieldCustom2: UITextFieldCustom!
@IBOutlet weak var textFieldCustom3: UITextFieldCustom!
override func viewDidLoad() {
super.viewDidLoad()
textFieldCustom1.delegate = textFieldCustom1
textFieldCustom2.delegate = textFieldCustom2
textFieldCustom3.delegate = textFieldCustom3
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
ソースファル