I am writing my first project on MVC architecture. I'm a beginner and might be missing out on a simple one. But I just can't figure out how to implement constraint in View and deliver it to Controller.
View:
import UIKit
class ViewExample: UIView {
var textView: UITextView = {
let textView = UITextView()
textView.translatesAutoresizingMaskIntoConstraints = false
textView.text = "Hello, world!"
return textView
}()
func setupViews() {
addSubview(textView)
NSLayoutConstraint.activate([
textView.topAnchor.constraint(equalTo: safeAreaLayoutGuide.topAnchor, constant: 10),
textView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 10),
textView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -10),
textView.heightAnchor.constraint(equalTo: textView.widthAnchor, multiplier: 2)
])
}
override init(frame: CGRect){
super.init(frame: frame)
setupViews()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setupViews()
}
}
Controller:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let ve = ViewExample()
ve.setupViews()
view.addSubview(ve)
}
}
What do I need to fix for this to work?
You didn't set the constraints for the view named ve
. I recommend you to use SnapKit
cocoapod. it helps you easy to set constraints for your views. And update like this.
import SnapKit
class ViewExample: UIView {
....
func setupViews() {
addSubview(textView)
textView.snp.makeConstraints {
$0.edges.equalToSuperview()
$0.height.equalTo(textView.snp.width).multipliedBy(2)
}
}
}
import SnapKit
class ViewController{
....
override func viewDidLoad() {
super.viewDidLoad()
let ve = ViewExample()
ve.setupViews()
view.addSubview(ve)
ve.snp.makeConstraints {
$0.top.equalToSuperview().offset(20)
$0.left.equalToSuperview().offset(20)
$0.right.equalToSuperview().offset(-20)
}
}
....
}
if you don't want to use SnapKit, add the following code to the viewDidLoad
method. First, add bottom constraint to textView
in setupViews
method.
let ve = ViewExample()
ve.setupViews()
view.addSubview(ve)
ve.translateAutoresizingMaskIntoConstraints = false
ve.topAnchor.constraint(equalTo: view.topAnchor, constant: 20).isActive = true
ve.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20).isActive = true
ve.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 20).isActive = true
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments