Skip to content

Instantly share code, notes, and snippets.

@KentarouKanno
Last active April 19, 2021 02:48
Show Gist options
  • Save KentarouKanno/34be40d51f8f53fe76c5 to your computer and use it in GitHub Desktop.
Save KentarouKanno/34be40d51f8f53fe76c5 to your computer and use it in GitHub Desktop.
UITextField

UITextField

★ UITextFieldの生成

var textField = UITextField()

var textField: UITextField = UITextField()

// 位置、サイズを指定して生成
var textField = UITextField(frame: CGRectMake(50, 50, 200, 50))

★ UITextFieldのサイズを設定

textField.frame = CGRectMake(50, 50, 100, 30)

★ UITextFieldの中心位置を設定

textField.layer.position = CGPoint(x:self.view.bounds.width/2,y:100)

textField.center = self.view.center

★ デリゲートを設定する

textField.delegate = self

★ セキュアなテキストフィールドを設定する

// (UITextInputTraits)設定する Default: false
textField.secureTextEntry = true

★ UITextFieldの文字列を設定/取得する

// 設定する
textField.text = "Swift Dict"

// 取得する
var textFieldString = textField.text

★ プレイスフォルダーを設定する

// default is nil. string is drawn 70% gray
textField.placeholder = "placeholder"

★ 文字色を設定する

textField.textColor = UIColor.redColor()

★ フォントを設定する

textField.font = UIFont.systemFontOfSize(12)

★ 背景色を設定する

textField.backgroundColor = UIColor.yellowColor()

★ 背画像を設定する

// UITextBorderStyle.RoundedRect以外のスタイルで表示される

textField.background = UIImage(named: "image")

★ 枠線のスタイルを設定する

textField.borderStyle = UITextBorderStyle.RoundedRect

textField.borderStyle = .Line

// UITextBorderStyle

/*
None 枠線なし
Line 四角い枠線
Bezel 立体的な四角い枠線
RoundedRect ノーマル
*/

★ 横揃えを設定する

// (NSText) Default: Left
extField.textAlignment = NSTextAlignment.Left

textField.textAlignment = .Center

// NSTextAlignment
/*
Left
Center
Right
*/

★ 縦揃えを設定する

textField.contentVerticalAlignment = UIControlContentVerticalAlignment.Center

textField.contentVerticalAlignment = .Bottom

// UIControlContentVerticalAlignment
/*
Center
Top
Bottom
Fill
*/

★ テキストフィールドの左側のViewにラベルを設定する

//透明なViewを置くことで左側のPaddingを調節することも可能

var label = UILabel(frame: CGRectMake(0, 0, 30, 30))
label.text = "ID"
label.textAlignment = NSTextAlignment.Center

// leftViewに設定(leftViewModeを設定しないと表示されない)
textField.leftView = label

★ テキストフィールドの左側のパディングを設定する

// 入力フィールドの左を10pxあける
let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 5))
paddingView.backgroundColor = UIColor.clearColor()
textField.leftView = paddingView
textField.leftViewMode = .Always

★ UITextFieldを継承したクラスで入力中、表示中の領域を変更することができる

// 左右にマージンを設ける場合
class CustomTextField: UITextField {
    // 表示領域
    override func textRectForBounds(bounds: CGRect) -> CGRect {
        return CGRectInset(bounds, 16.0, 0)
    }
    // 入力中の表示領域
    override func editingRectForBounds(bounds: CGRect) -> CGRect {
        return CGRectInset(bounds, 16.0, 0)
    }
}

// 左のみのマージンを設定する場合
class CustomTextField: UITextField {
    let leftMargin: CGFloat = 15
    
    // 表示領域
    override func textRectForBounds(bounds: CGRect) -> CGRect {
        return CGRectMake(bounds.origin.x + leftMargin, bounds.origin.y, bounds.size.width - leftMargin, bounds.size.height)
    }
    
    // 入力中の表示領域
    override func editingRectForBounds(bounds: CGRect) -> CGRect {
        return CGRectMake(bounds.origin.x + leftMargin, bounds.origin.y, bounds.size.width - leftMargin, bounds.size.height)
    }
}

★ テキストフィールドの左側のViewの表示を設定する

textField.leftViewMode = UITextFieldViewMode.WhileEditing

textField.leftViewMode = .Always

★ テキストフィールドの右側のViewに画像を設定する

//透明なViewを置くことで右側のPaddingを調節することも可能

var imageView = UIImageView(image: UIImage(named: "image"))
imageView.frame = CGRectMake(0, 0, 30, 30)
        
// rightViewに設定(rightViewModeを設定しないと表示されない)
textField.rightView = imageView

// ※rightViewを表示するとクリアボタンは表示されなくなります

★ テキストフィールドの右側のViewの表示を設定する

textField.rightViewMode = UITextFieldViewMode.UnlessEditing

textField.rightViewMode = .Always

★ クリアボタンの表示を設定する

textField.clearButtonMode = UITextFieldViewMode.WhileEditing

textField.clearButtonMode = .Always

// UITextFieldViewMode

/*
Never 表示しない
WhileEditing フォーカスが当たっている時のみ表示する
UnlessEditing フォーカスが当たっていない時のみ表示する
Always 常に表示する
*/

★ TextFieldの自動補完が有効であるかどうかを決定する

textField.autocorrectionType = .No

// UITextAutocorrectionType
  
/*  
Default
No
Yes
*/

★ 入力時のキーボードのreturnキーの表示を指定する

// (UITextInputTraits)
textField.returnKeyType = UIReturnKeyType.Go
        
textField.returnKeyType = .Done

// UIReturnKeyType
/*
Default
Go
Google
Join
Next
Route
Search
Send
Yahoo
Done
EmergencyCall
*/

★ 入力時のキーボードを指定する

// (UITextInputTraits)
textField.keyboardType = UIKeyboardType.URL
        
textField.keyboardType = .NumberPad

// UIKeyboardType
/*
Default
ASCIICapable
NumbersAndPunctuation
URL
NumberPad
PhonePad
NamePhonePad
EmailAddress
DecimalPad
Twitter
WebSearch
*/

★ テキストフィールドにフォーカスを当て、キーボードを表示する

textField.becomeFirstResponder()

★ テキストフィールドからフォーカスを外し、キーボードを非表示にする

textField.resignFirstResponder()

★ 画面タップ時にキーボードを非表示にする

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    self.view.endEditing(true)
}

★ Textfieldにイベントが発生した時に呼ばれるメソッドを設定する

textField.addTarget(self, action: "editingDidEnd", forControlEvents: .EditingDidEnd)

func editingDidEnd() {
    print("editingDidEnd")
}

★ Viewにテキストフィールドを追加する

self.view.addSubview(textField)

★ TextFielの入力を他のTextFieldに反映する
※TextFieldの入力を日本語の変換途中も取得する

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var textField1: UITextField!
    @IBOutlet weak var textField2: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Swift2.2
        textField1.addTarget(self , action: #selector(changeText(_:)), forControlEvents: .EditingChanged)
        // Swift2.1まで
        //textField1.addTarget(self , action: Selector("changeText:"), forControlEvents: .EditingChanged)
    }

    func changeText(textField: UITextField)  {
        textField2.text = textField.text
    }
}

★ TextFieldの入力時の変更を通知で受け取る  

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var textField: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 入力値が変更された時に呼ばれる通知を登録
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(self.didChangeNotification(notification:)),
            name: NSNotification.Name.UITextFieldTextDidChange,
            object: nil
        )
    }
    
    // 入力値が変更された時に呼ばれるメソッド
    func didChangeNotification(notification: Notification) {
        
        if let textField = notification.object as? UITextField,
            let text = textField.text {
            
        }
    }
    
    // 通知の解除
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}

★ textField.borderStyle = .none で入力時文字列がずれるのでその対応

class CustomTextField: UITextField {
    
    override func textRect(forBounds bounds: CGRect) -> CGRect {
        return bounds.insetBy(dx: 2, dy: 1)
    }
    
    override func editingRect(forBounds bounds: CGRect) -> CGRect {
        return bounds.insetBy(dx: 2, dy: 1)
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment