【发布时间】:2020-07-20 16:19:49
【问题描述】:
我有一个项目,它有一个 viewController,里面有一个滚动视图,它有一个 UILabel 和一个 UITextView 作为子视图。每次打开应用程序时,我都会从 Google Firestore 数据库中检索数据,因此将 UILabel 更新为标题,将 UITextView 更新为文本正文。我已经设置了约束,一切都运行良好。但是,如果 textView 的大小超出 UIViewController 视图的边界,我不知道如何计算 UIScrollView 的 contentView 高度,以便您可以向下滚动以阅读其余文本。我在底部也有一个 tabBar,这意味着滚动视图应该停止在它上面。
这是我的代码。
import UIKit
class StoryViewController: UIViewController {
var storyTitle = String()
var storyBody = ""
let titleLabel: UILabel = {
let label = UILabel()
label.textAlignment = .center
label.numberOfLines = 0
label.font = UIFont(name: "Arial-BoldMT", size: 28)
label.textColor = UIColor.black
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
let textView: UITextView = {
let textView = UITextView()
textView.textAlignment = .left
textView.isEditable = false
textView.isSelectable = false
textView.font = UIFont(name: "ArialMT", size: 19)
textView.isScrollEnabled = false
textView.translatesAutoresizingMaskIntoConstraints = false
return textView
}()
let scrollView: UIScrollView = {
let scrollingView = UIScrollView()
scrollingView.translatesAutoresizingMaskIntoConstraints = false
return scrollingView
}()
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.shadowImage = UIImage()
self.view.backgroundColor = UIColor.white
titleLabel.text = storyTitle
textView.text = storyBody.replacingOccurrences(of: "NL", with: "\n\n")
textView.sizeToFit()
scrollView.contentSize = CGSize(width: self.view.frame.width, height: textView.contentSize.height)
view.addSubview(scrollView)
scrollView.addSubview(titleLabel)
scrollView.addSubview(textView)
NSLayoutConstraint.activate([
scrollView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
titleLabel.leadingAnchor.constraint(equalTo: scrollView.readableContentGuide.leadingAnchor),
titleLabel.trailingAnchor.constraint(equalTo: scrollView.readableContentGuide.trailingAnchor),
titleLabel.topAnchor.constraint(equalTo: scrollView.topAnchor, constant: 16),
titleLabel.bottomAnchor.constraint(equalTo: textView.topAnchor, constant: -16),
titleLabel.centerXAnchor.constraint(equalTo: scrollView.centerXAnchor),
textView.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 16),
textView.centerXAnchor.constraint(equalTo: scrollView.centerXAnchor),
textView.leadingAnchor.constraint(equalTo: scrollView.readableContentGuide.leadingAnchor),
textView.trailingAnchor.constraint(equalTo: scrollView.readableContentGuide.trailingAnchor),
])
我尝试了很多东西,但似乎没有任何效果。
提前感谢大家的时间和回复。
【问题讨论】:
标签: ios swift uiscrollview uitextview