如何解决以编程方式构建的Swift TextField的大小是否不适合屏幕宽度?
我已经以编程方式定义了一个textField,以在屏幕的宽度上延伸(通过约束,每边少50个点作为“边距”。左侧(前导)效果很好,但textField的宽度仅与文本一样宽而不是跨越到右侧(后方)的50个点之内。屏幕截图底部的按钮也存在相同的问题(附后)。由于它们的尺寸不正确,它们肯定是相关的吗?!
我认为令人讨厌的/被忽略的约束是NSLayoutConstraint.activate中的第三行,我在其中将TrailingAnchor约束设置为-50。
我的代码如下:
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)
])
}
TextField在以下类中定义:
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"
}
}
ScreenShot of the TextField (2nd element from top)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。