[英]Swift view is not showing up
I'm trying to create a UITextView
on my main view, I managed to do it with textView = UITextView(frame: CGRect(x: 10, y: 10, width: 300, height: 300))
however, I can't do it with constraints for some reasons. 我正在尝试在我的主视图上创建一个
UITextView
,我设法用textView = UITextView(frame: CGRect(x: 10, y: 10, width: 300, height: 300))
但是,我不能出于某些原因,我可以使用约束。 Here's my function that I call in viewDidLoad()
: 这是我在
viewDidLoad()
调用的函数:
private func configureTextView() {
view.addSubview(textView)
textView.topAnchor.constraint(equalTo: view.topAnchor, constant: 10)
textView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 10)
textView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -10)
textView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -10)
textView.backgroundColor = .red
print(view.subviews)
}
And here's the textView
: 这是
textView
:
private let textView: UITextView = {
let view = UITextView()
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
I'm still a very beginner, but print(view.subviews)
shows that textView
is a subview of the main view (I guess) 我还是一个很初级,但
print(view.subviews)
显示textView
是主视图的子视图(我猜)
[<UITextView: 0x7fdf64809600; frame = (0 0; 0 0); text = '';
clipsToBounds = YES; gestureRecognizers = <NSArray: 0x60000062f450>;
layer = <CALayer: 0x60000083b360>; contentOffset: {0, 0}; contentSize:
{0, -8}; adjustedContentInset: {0, 0, 0, 0}>]
You create constraints, but never set them as active. 您创建约束,但从不将它们设置为活动。 Changing to this should help make it display properly:
更改为此应有助于使其正确显示:
textView.topAnchor.constraint(equalTo: view.topAnchor, constant: 10).isActive = true
textView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 10).isActive = true
textView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -10).isActive = true
textView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -10).isActive = true
You can also use "SnapKit" 你也可以使用“SnapKit”
https://github.com/SnapKit/SnapKit https://github.com/SnapKit/SnapKit
pod 'SnapKit', '~> 5.0.0'
pod'SnapKit','〜> 5.0.0'
self.addSubView(textView)
textView.snp.makeConstraints { (make) -> Void in
make.top.equalTo(0)
make.bottom.equalTo(0)
make.left.equalTo(0)
make.right.equalTo(0)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.