文本视图不显示在滚动视图中



我有一个视图控制器名称为TeamDetailsViewController。 我以编程方式将滚动视图添加到视图控制器,并将 UITextview 添加为滚动视图的子视图。但是文本视图由于未知原因未显示。请帮忙。这是我的代码

class TeamDetailsController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.navigationBar.prefersLargeTitles = false
setupViews()
}
lazy var scrollView: UIScrollView = {
let sv = UIScrollView(frame: self.view.bounds)
sv.backgroundColor = .blue
sv.autoresizingMask = UIViewAutoresizing(rawValue: UIViewAutoresizing.RawValue(UInt8(UIViewAutoresizing.flexibleWidth.rawValue) | UInt8(UIViewAutoresizing.flexibleHeight.rawValue)))
sv.contentSize = CGSize(width: self.view.bounds.size.width, height: self.view.bounds.size.height * 2);
return sv
}()
var textView: UITextView = {
var tv = UITextView()
tv.textColor = .darkGray
tv.backgroundColor = .black
tv.font = UIFont.systemFont(ofSize: 16)
return tv
}()
func setupViews() {
view.backgroundColor = .white
view.addSubview(scrollView)            
scrollView.addSubview(textView)
scrollView.addConstraintsWithFormat(format: "H:|-16-[v0]-16-|", views: textView)
scrollView.addConstraintsWithFormat(format: "V:|-16-[v0]-16-|", views: textView)           
}
}

试试这段代码;

var textView: UITextView = {
var tv = UITextView()
tv.textColor = .darkGray
tv.backgroundColor = .black
tv.translatesAutoresizingMaskIntoConstraints = false
tv.font = UIFont.systemFont(ofSize: 16)
return tv
}()

在此变体中将 scrollView contentSize 显式设置为框架,您不应对 scrollView 的子视图使用自动布局约束。试试这个:

func setupViews() {
view.backgroundColor = .white
view.addSubview(scrollView)
scrollView.addSubview(textView)
textView.frame = CGRect.init(origin: CGPoint(0, 0), size: scrollView.contentSize).insetBy(dx: 16, dy: 16)
}

另一种变体是不将滚动视图内容大小显式设置为框架,并使滚动视图子视图约束到滚动视图的边缘,并通过约束设置此子视图的高度和宽度,scrollView 将从该宽度和高度约束中获取内容大小。例:

view.addSubview(scrollView)
scrollView.topAnchor.constraint(equalTo: view.topAnchor, constant: 0).isActive = true
scrollView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 0).isActive = true
scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true
scrollView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 0).isActive = true
scrollView.addSubview(imageView)
imageView.topAnchor.constraint(equalTo: scrollView.topAnchor, constant: 0).isActive = true
imageView.leftAnchor.constraint(equalTo: scrollView.leftAnchor, constant: 0).isActive = true
imageView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor, constant: 0).isActive = true
imageView.rightAnchor.constraint(equalTo: scrollView.rightAnchor, constant: 0).isActive = true
imageView.widthAnchor.constraint(equalToConstant: UIScreen.main.bounds.width).isActive = true
imageView.heightAnchor.constraint(equalToConstant: view.frame.height - 32).isActive = true

不要忘记设置滚动视图及其子视图

scrollView.translatesAutoresizingMaskIntoConstraints = false
imageView.translatesAutoresizingMaskIntoConstraints = false

最新更新