我想在屏幕上半部分相对于设备方向的中心显示 YouTube 视频封面(长宽比为 16:9)。我如何在 Xcode 故事板中实现它?
到目前为止我所做的:
StackView 有什么意义?我试图限制子视图的高度,同时使用“Aspect Fit”内容模式保持纵横比。
不需要堆栈视图......
让我们创建一个带有红色背景的
UIView
- 这将是您的视频视图(或它的“支架”):
let v16x9 = UIView()
v16x9.backgroundColor = .red
v16x9.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(v16x9)
为了减少打字,请声明安全区域:
let g = view.safeAreaLayoutGuide
现在的限制:
NSLayoutConstraint.activate([
// top to top of safe area
v16x9.topAnchor.constraint(equalTo: g.topAnchor),
// center horizontally
v16x9.centerXAnchor.constraint(equalTo: g.centerXAnchor),
// keep the width less-than-or-equal-to the safe area
v16x9.widthAnchor.constraint(lessThanOrEqualTo: g.widthAnchor),
// view height is 16:9 ratio
v16x9.heightAnchor.constraint(equalTo: v16x9.widthAnchor, multiplier: 9.0 / 16.0),
// keep height less-than-or-equal-to one-half (50%) of the safe area
v16x9.heightAnchor.constraint(lessThanOrEqualTo: g.heightAnchor, multiplier: 0.5),
])
// stretch the view as wide as possible, while respecting the other constraint restrictions
let wc: NSLayoutConstraint = v16x9.widthAnchor.constraint(equalTo: g.widthAnchor)
wc.priority = .defaultHigh
wc.isActive = true