8
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Swift] ストーリーボード上でプロパティ指定可能なUIパーツの作り方(UITextField拡張)

Last updated at Posted at 2016-05-05

概要

フォーカス時に背景色が変わるUITextFieldを作ってみました。
背景色はストーリーボードで指定できるようにしています。

動作イメージ

FocusColorTest.gif

開発環境

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拡張クラスを指定します。
Screen1.png

UITextField拡張クラスのコードに@IBInspectable var focusBkColor: UIColor?の記述をすることで、Attribute InspectorにFocus Bk Colorというプロパティが出現します。
Screen2.png
このプロパティにて、フォーカス時の背景色を指定できるようにしてみました。

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()
    }
    
}

ソースファル

8
8
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?