我有一个带有滚动视图的UIViewController,一个以编程方式添加了字段的内容视图。文本视图已禁用滚动。当用户键入文本视图时,其大小会增加,但不会在键盘上方向上移动。此外,滚动没有滚动正确的视图。请检查附件中的project。
extension ScrollViewController: UITextViewDelegate {
func textViewDidChange(_ textView: UITextView) {
let fixedWidth = textView.frame.size.width
var newSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
if newSize.height < 200 {
newSize.height = 200
}
textView.frame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height)
if let constraint = (body.constraints.filter { $0.firstAttribute == .height }.first) {
constraint.constant = newSize.height
}
textView.layoutIfNeeded()
}
}
约束代码:
func addConstraints() {
// scroll view
NSLayoutConstraint.activate([
scrollView.topAnchor.constraint(equalTo: view.topAnchor, constant: 8.0),
scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 8.0),
scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -8.0),
scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -8.0)
])
// content view
NSLayoutConstraint.activate([
contentView.topAnchor.constraint(equalTo: view.topAnchor),
contentView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
contentView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
contentView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
contentView.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 1.0)
])
// title text field
NSLayoutConstraint.activate([
titleText.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 100),
titleText.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 8.0),
titleText.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -8.0),
titleText.bottomAnchor.constraint(equalTo: body.topAnchor, constant: -8.0),
titleText.heightAnchor.constraint(equalToConstant: 31)
])
// body text view
NSLayoutConstraint.activate([
body.topAnchor.constraint(equalTo: titleText.bottomAnchor, constant: 8.0),
body.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 8.0),
body.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -8.0),
body.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -40),
body.heightAnchor.constraint(equalToConstant: 200)
])
}
答案 0 :(得分:0)
答案 1 :(得分:0)
*tmp*
使用此代码,您的问题将得到解决。 代码的主要问题是锚定 contentView ,并且您将标题文本字段bottomAnchor赋予body.topAnchor,这会导致您的正文文本视图高度。