我有一个视图控制器名称为TeamDetailsViewController。 我以编程方式将滚动视图添加到视图控制器,并将UITextview添加为滚动视图的子视图。但是由于未知原因,Text View不会显示。请帮忙。这是我的代码
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)
}
}
答案 0 :(得分:0)
尝试此代码;
var textView: UITextView = {
var tv = UITextView()
tv.textColor = .darkGray
tv.backgroundColor = .black
tv.translatesAutoresizingMaskIntoConstraints = false
tv.font = UIFont.systemFont(ofSize: 16)
return tv
}()
答案 1 :(得分:0)
在此变体中,您将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 contentSize显式设置为框架,并使您的scrollView subViews约束位于scrollView的边缘,并使用约束设置该subViews的高度和宽度,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
别忘了设置scrollViews及其子视图
scrollView.translatesAutoresizingMaskIntoConstraints = false
imageView.translatesAutoresizingMaskIntoConstraints = false