Reputation: 13
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. Here's my function that I call in 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
:
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)
[<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}>]
Upvotes: 1
Views: 190
Reputation: 56
You can also use "SnapKit"
https://github.com/SnapKit/SnapKit
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)
}
Upvotes: 1
Reputation: 1192
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
Upvotes: 3