Skip to content

Instantly share code, notes, and snippets.

@DaisukeNagata
Created December 17, 2019 11:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DaisukeNagata/253ae79692234dbf89d042f5010f2387 to your computer and use it in GitHub Desktop.
Save DaisukeNagata/253ae79692234dbf89d042f5010f2387 to your computer and use it in GitHub Desktop.
StoryBoard_UITestField_CaretLogic
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
}
}
@DaisukeNagata
Copy link
Author

gifImage2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment