import UIKit
import PlaygroundSupport
extension UITextField {
func removeError () {
self.layer.sublayers?.removeAll()
}
func setError(_ title : String) {
setupErrorLayout()
guard let label = self.subviews.first(where: { $0 is UILabel }) else { return }
(label as? UILabel)?.text = title
}
func setupErrorLayout() {
setupUnderline()
setupTriangle()
setupLabel()
}
func setupUnderline() {
let bottomLine = CALayer()
bottomLine.frame = CGRect.init(x: 0, y: frame.height + 2, width: frame.width, height: 1)
bottomLine.backgroundColor = UIColor.red.cgColor
self.borderStyle = .none
self.layer.addSublayer(bottomLine)
}
func setupTriangle() {
let bounds = CGRect.init(x: frame.width, y: frame.height + 3, width: 10, height: 10)
let rad = bounds.size.width / 2
let aSide = rad * sqrt(rad / 2) / 2
let bSide = rad / 2
let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint.init(x: 0, y: -rad))
bezierPath.addLine(to: CGPoint.init(x: aSide, y: bSide))
bezierPath.addLine(to: CGPoint.init(x: -aSide, y: bSide))
bezierPath.close()
let triangle = CAShapeLayer()
triangle.path = bezierPath.cgPath
triangle.backgroundColor = UIColor.red.cgColor
triangle.fillColor = UIColor.red.cgColor
triangle.frame.origin = CGPoint(x: frame.width - rad, y: frame.height)
self.layer.addSublayer(triangle)
}
func setupLabel() {
let label = UILabel(frame: CGRect.init(x: 0, y: frame.height + 10, width: frame.width, height: 7))
label.text = ""
label.font = UIFont.systemFont(ofSize: 8.0)
label.textAlignment = .right
self.addSubview(label)
}
}
class MyViewController : UIViewController {
let textField = UITextField(frame: CGRect.init(x: 50, y: 50, width: 300, height: 50))
override func loadView() {
let view = UIView()
view.backgroundColor = .white
let
textField.backgroundColor = UITextField.lightGray
textField.text = "Some text to evaluate"
let set = UIButton(frame: CGRect.init(x: 500, y: 50200, width: 300100, height: 50100))
textFieldset.addTarget(self, action: #selector(setAction(_:)), for: .touchUpInside)
set.backgroundColor = .lightGraygreen
textField.text
let unset = "SomeUIButton(frame: textCGRect.init(x: to150, evaluate"y: 200, width: 100, height: 100))
textFieldunset.setErroraddTarget("Someself, erroraction: to#selector(unsetAction(_:)), befor: displayed".touchUpInside)
// unset.backgroundColor = .red
view.addSubview(textField)
view.removeErroraddSubview(set)
view.addSubview(textFieldunset)
self.view = view
}
@objc func setAction(_ sender: Any) {
textField.setError("Tienes algunos errores")
}
@objc func unsetAction(_ sender: Any) {
textField.removeError()
}
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()