即使内容被推出屏幕,UIScrollView也不会滚动



我正在学习以编程方式使用UIScrollView

我创建了一个滚动视图,锚定为全屏,然后添加了 2 个元素。

一个锚定在顶部,另一个锚定在一个位置,应该将其推离屏幕。

我希望视图滚动到它,但它没有。它只是保持固定。

我一直在阅读许多答案,但找不到适用于我以下观点的方法

class ViewController: UIViewController {
lazy var scrollView = UIScrollView(frame: .zero)
lazy var usernameTF = createTextField(nil, placeholder: "username", type: .emailAddress)
lazy var passwordTF = createTextField(nil, placeholder: "password", type: .default, isSecureEntry: true)
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
view.backgroundColor = .white
[scrollView, usernameTF, passwordTF].forEach { $0.translatesAutoresizingMaskIntoConstraints = false }
view.addSubview(scrollView)
[usernameTF, passwordTF].forEach { scrollView.addSubview($0) }
NSLayoutConstraint.activate([
scrollView.topAnchor.constraint(equalTo: view.topAnchor),
scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
usernameTF.topAnchor.constraint(equalTo: scrollView.topAnchor, constant: 32),
usernameTF.widthAnchor.constraint(equalTo: scrollView.widthAnchor, constant: -32),
usernameTF.heightAnchor.constraint(equalToConstant: 40),
usernameTF.centerXAnchor.constraint(equalTo: scrollView.centerXAnchor),
passwordTF.topAnchor.constraint(equalTo: usernameTF.bottomAnchor, constant: 1600),
passwordTF.widthAnchor.constraint(equalTo: scrollView.widthAnchor, constant: -32),
passwordTF.heightAnchor.constraint(equalToConstant: 40),
passwordTF.centerXAnchor.constraint(equalTo: scrollView.centerXAnchor)
])
}
func createTextField(_ delegate: UITextFieldDelegate?, placeholder: String, type: UIKeyboardType, isSecureEntry: Bool = false) -> UITextField {
let tf = UITextField(frame: .zero)
tf.placeholder = placeholder
tf.backgroundColor = .init(white: 0, alpha: 0.03)
tf.borderStyle = .roundedRect
tf.font = .systemFont(ofSize: 14)
tf.keyboardType = type
tf.autocapitalizationType = .none
tf.autocorrectionType = .no
tf.isSecureTextEntry = isSecureEntry
if let delegate = delegate {
tf.delegate = delegate
}
return tf
}
}

您需要添加底部锚点,将 passwordTF 底部连接到滚动视图底部。因此,滚动视图可以计算出它的内容高度。

passwordTF.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor)

最新更新