I have programmatically defined a textField to stretch across the width of the screen (less 50 points as a "margin" on each side via constraints. The left (leading) side works fine but the textField is only as wide as the text rather than spanning to within 50 points of the right (trailing) side. Also having the same issue with the button at the bottom of the screenshot (attached). Surely they must be related as they are the same incorrect size?!
I believe the offending / ignored constraint is the 3rd line within the NSLayoutConstraint.activate where I set the trailingAnchor constraint to -50.
My code follows:
func configureTextField() {
view.addSubview(usernameTextField)
NSLayoutConstraint.activate([
usernameTextField.topAnchor.constraint(equalTo: logoImageView.bottomAnchor, constant: 48),
usernameTextField.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 50),
usernameTextField.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -50),
usernameTextField.heightAnchor.constraint(equalToConstant: 50)
])
}
The TextField is defined in the following Class:
import UIKit
class GFTextField: UITextField {
override init(frame: CGRect) {
super.init(frame: frame)
configure()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func configure() {
translatesAutoresizingMaskIntoConstraints = false
layer.cornerRadius = 10
layer.borderWidth = 2
layer.borderColor = UIColor.systemGray4.cgColor
textColor = .label
tintColor = .label
textAlignment = .center
font = UIFont.preferredFont(forTextStyle: .title2)
adjustsFontSizeToFitWidth = true
minimumFontSize = 12
backgroundColor = .tertiarySystemBackground
autocorrectionType = .no
placeholder = "Enter a username"
}
}