I figured out. Although I do not know why this happens, whether it's a bug with UIScrollView
or things just have to be done this way.
Apparently, when you add subviews to a UIScrollView
in Story Board, you'll always get a warning saying that the position of the subviews are ambiguous. So, what you would do is to add a UIView
to the scroll view and add these constraints to it:
Top = 0, Leading = 0, Trailing = 0 and Bottom = 0
UIView
is centered both horizontally and vertically in the scroll view
After that, you're good to add subviews to UIView
without getting those warnings.
Same reason applies here, when you want to add subviews to a UIScrollView
programmatically, and also set up some constraints, you should put a UIView
inside the scroll view and put all subviews inside the UIView
:
let subviewContainer = UIView.init(frame: .zero)
subviewContainer.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(subviewContainer)
var constraints: [NSLayoutConstraint] = []
// Step 1, set up horizontal constraints to make leading & trailing = 0
constraints += NSLayoutConstraint.constraints(
withVisualFormat: "H:|-0-[subviewContainer]-0-|",
options: [],
metrics: nil,
views: ["subviewContainer": subviewContainer]
)
// Step 2, set up vertical constraints to make top & bottom = 0
constraints += NSLayoutConstraint.constraints(
withVisualFormat: "V:|-0-[subviewContainer]-0-|",
options: [],
metrics: nil,
views: ["subviewContainer": subviewContainer]
)
// **Step 3, center "subviewContainer" horizontally & vertically in scroll view**
constraints.append(
NSLayoutConstraint.init(
item: subviewContainer,
attribute: .centerX,
relatedBy: .equal,
toItem: scrollView,
attribute: .centerX,
multiplier: 1,
constant: 0
)
)
constraints.append(
NSLayoutConstraint.init(
item: subviewContainer,
attribute: .centerY,
relatedBy: .equal,
toItem: scrollView,
attribute: .centerY,
multiplier: 1,
constant: 0
)
)
// Step 4, activate all constraints
NSLayoutConstraint.activate(constraints)
After these 4 steps, you are now good to add subviews to "subviewContainer".