Created
December 17, 2019 11:29
-
-
Save DaisukeNagata/253ae79692234dbf89d042f5010f2387 to your computer and use it in GitHub Desktop.
StoryBoard_UITestField_CaretLogic
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
final class UnderLineTextField: UITextField { | |
private var border: CALayer | |
override init(frame: CGRect) { | |
border = CALayer() | |
super.init(frame: .zero) | |
} | |
required init?(coder: NSCoder) { | |
border = CALayer() | |
super.init(coder: coder) | |
} | |
func underLineTextField(height: CGFloat) { | |
self.borderStyle = UITextField.BorderStyle.none | |
border.frame = CGRect(x: 0, y: self.frame.height - height, width: self.frame.width, height: height) | |
self.layer.addSublayer(border) | |
self.addTarget(self, action: #selector(textFieldDidChange),for: UIControl.Event.editingChanged) | |
} | |
func addBorderBottom() { border.backgroundColor = UIColor.gray.cgColor } | |
func addBorderReset() { border.backgroundColor = UIColor.blue.cgColor } | |
@objc func textFieldDidChange (textFiled: UnderLineTextField) { | |
guard textFiled.text?.isEmpty == false else { | |
addBorderBottom() | |
return | |
} | |
addBorderReset() | |
} | |
} | |
class ViewController: UIViewController { | |
@IBOutlet weak var textFieldOne: UnderLineTextField! | |
@IBOutlet weak var textFieldSecound: UnderLineTextField! | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
textFieldOne.delegate = self | |
textFieldSecound.delegate = self | |
textFieldOne.underLineTextField(height: 1) | |
textFieldOne.addBorderBottom() | |
textFieldSecound.underLineTextField(height: 1) | |
textFieldSecound.addBorderBottom() | |
} | |
} | |
// 今フォーカスが当たっているテキストボックスからフォーカスを外す | |
extension ViewController: UITextFieldDelegate { | |
func textFieldShouldReturn(_ textField: UITextField) -> Bool { | |
if textField == textFieldOne { | |
textFieldOne.resignFirstResponder() | |
textFieldSecound.becomeFirstResponder() | |
} else { | |
textFieldSecound.resignFirstResponder() | |
textFieldOne.becomeFirstResponder() | |
} | |
return true | |
} | |
} |
Author
DaisukeNagata
commented
Dec 17, 2019
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment