I’ve gone through this challenge and got it to work for both addConstraint(NSLayoutConstraint(item:Attribute:relatedBy:toItem:attribute:multiplier:constant:) and by NSLayoutConstraints.constraints(withVisualFormat:options:metric:views:) as the book wanted.
While reading documentation and other sources on the web I learned of Layout Anchors. One site even said how much easier they were. Not for me yet. I’ve tried to get them to work for this challenge and can’t get it. I must be missing something. Anybody fluent in Layout Anchors? Here is what I have:
removeButton.translatesAutoresizingMaskIntoConstraints = false
addEmployeeButton.translatesAutoresizingMaskIntoConstraints = false
scrollView.translatesAutoresizingMaskIntoConstraints = false
let superview = scrollView.superview!
scrollView.leadingAnchor.constraint(equalTo: superview.leadingAnchor, constant: 20.0).isActive = true
scrollView.topAnchor.constraint(equalTo: superview.topAnchor, constant: 20).isActive = true
scrollView.bottomAnchor.constraint(equalTo: superview.bottomAnchor, constant: -20.0).isActive = true
scrollView.widthAnchor.constraint(greaterThanOrEqualToConstant: 250.0).isActive = true
scrollView.heightAnchor.constraint(greaterThanOrEqualToConstant: 100.0).isActive = true
addEmployeeButton.leadingAnchor.constraint(equalTo: scrollView.trailingAnchor, constant: 20.0).isActive = true
addEmployeeButton.topAnchor.constraint(equalTo: superview.topAnchor, constant: 20.0).isActive = true
addEmployeeButton.trailingAnchor.constraint(equalTo: superview.trailingAnchor, constant: -20.0).isActive = true
removeButton.widthAnchor.constraint(equalTo: addEmployeeButton.widthAnchor, constant: 0.0).isActive = true
removeButton.topAnchor.constraint(equalTo: addEmployeeButton.bottomAnchor, constant: 20.0).isActive = true
removeButton.leadingAnchor.constraint(equalTo: scrollView.trailingAnchor, constant: 20.0).isActive = true
removeButton.trailingAnchor.constraint(equalTo: superview.trailingAnchor, constant: -20.0).isActive = true
removeButton.bottomAnchor.constraint(greaterThanOrEqualTo: superview.bottomAnchor,
constant: 20.0).isActive = true
and here is the result:
The height cannot be adjusted. The width can, but the Add Employee button stays oversized. And there is no Remove button visible. I’m not sure what made the Add Employee button oversized. And, this didn’t seem any easier than the first option. The visual layout seemed the easiest to me.
Here is what is supposed to look like (using the visual layout):
And this view is adjustable in width and height while the buttons remain in the current position and current size.
Thanks for any suggestions. It’s not crucial I get through this part, since it’s not in the book, but I figure Layout Anchors came out after the book was published and the authors would have included them if they had been out, so I should try to learn how to use them.