class TextFieldWTitle: UITextField { var titleText: String = "" { didSet { label.text = titleText } } var label = UILabel() override init(frame: CGRect) { super.init(frame: frame) self.genericConfigure() } init() { super.init(frame: CGRect.zero) self.genericConfigure() } required init?(coder: NSCoder) { super.init(coder: coder) self.genericConfigure() } func configure(text: String, placeholder: String = "") { self.text = text self.placeholder = placeholder if #available(iOS 13.0, *) { self.applyStyle13() } else { self.applyStylePre13() } } func genericConfigure() { self.borderStyle = .none self.layer.borderWidth = 1.0 self.layer.masksToBounds = false // true self.layer.cornerRadius = 4.0 self.textAlignment = .left label.text = "First name" label.translatesAutoresizingMaskIntoConstraints = false addSubview(label) NSLayoutConstraint.activate([ label.leftAnchor.constraint(equalTo: leftAnchor), label.bottomAnchor.constraint(equalTo: topAnchor), label.heightAnchor.constraint(equalToConstant: 20.0) ]) } @available(iOS 13.0, *) func applyStyle13() { self.tintColor = UIColor.label self.backgroundColor = UIColor.white self.textColor = UIColor.label self.attributedPlaceholder = NSAttributedString( string: self.placeholder ?? "", attributes: [NSAttributedString.Key.foregroundColor: UIColor.tertiaryLabel]) } func applyStylePre13() { self.tintColor = .yellow self.backgroundColor = UIColor.white self.textColor = .yellow self.attributedPlaceholder = NSAttributedString( string: self.placeholder ?? "", attributes: [NSAttributedString.Key.foregroundColor: UIColor.yellow]) } } class TitleFieldViewController : UIViewController { override func loadView() { let view = UIView() view.backgroundColor = .white let stack = UIStackView() //stack.frame = CGRect(x: 150, y: 200, width: 200, height: 200) stack.distribution = .fill stack.axis = .vertical let t1 = TextFieldWTitle() t1.configure(text: "texta", placeholder: "placeholder") let t2 = TextFieldWTitle() t2.configure(text: "textb", placeholder: "placeholder") t2.titleText = "Last name" stack.addArrangedSubview(t1) stack.addArrangedSubview(t2) view.addSubview(stack) stack.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ stack.topAnchor.constraint(equalTo: view.topAnchor, constant: 100), stack.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 100), stack.widthAnchor.constraint(equalToConstant: 200), ]) self.view = view // run first *without* spacing // then run *with* spacing //stack.spacing = 40 } } // Present the view controller in the Live View window PlaygroundPage.current.liveView = TitleFieldViewController()