【发布时间】:2020-06-22 03:26:04
【问题描述】:
我正在为我的自动布局使用扩展:
extension UIView{
func anchorSize(to view: UIView){
widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
heightAnchor.constraint(equalTo: view.heightAnchor).isActive = true
}
func anchor(top: NSLayoutYAxisAnchor?, leading: NSLayoutXAxisAnchor?, bottom: NSLayoutYAxisAnchor?, trailing: NSLayoutXAxisAnchor?, padding: UIEdgeInsets = .zero, size: CGSize = .zero){
translatesAutoresizingMaskIntoConstraints = false
if let top = top{
topAnchor.constraint(equalTo: top, constant: padding.top).isActive = true
}
if let leading = leading{
leadingAnchor.constraint(equalTo: leading, constant: padding.left).isActive = true
}
if let trailing = trailing{
trailingAnchor.constraint(equalTo: trailing, constant: padding.right).isActive = true
}
if let bottom = bottom{
bottomAnchor.constraint(equalTo: bottom, constant: padding.bottom).isActive = true
}
if size.width != 0 {
widthAnchor.constraint(equalToConstant: size.width).isActive = true
}
if size.height != 0 {
heightAnchor.constraint(equalToConstant: size.height).isActive = true
}
}
}
但是,我遇到了一个问题,在不同的屏幕尺寸上显示我的视图时,视图会被挤压或根本不适合。我将如何通过自动布局调整视图大小以适应多种屏幕尺寸?这也是我将约束应用于标签之类的代码:
logo.anchor(top: view.safeAreaLayoutGuide.topAnchor, leading: view.safeAreaLayoutGuide.leadingAnchor, bottom: nil, trailing: view.safeAreaLayoutGuide.trailingAnchor, padding: .init(top: 20, left: 0, bottom: 0, right: 0))
logo.centerXAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerXAnchor).isActive = true
subLogo.anchor(top: logo.bottomAnchor, leading: logo.leadingAnchor, bottom: nil, trailing: logo.trailingAnchor, padding: .init(top: 20, left: 0, bottom: 0, right: 0))
subLogo.centerXAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerXAnchor).isActive = true
iPhone 11 是我自动布局的正确方式。我真的很想为其他设备调整所有视图的大小。
Here are the screenshots of the example devices
提前致谢。
【问题讨论】:
-
您好,我认为您在 viewdidload() 中添加了代码,将代码移至查看 didLayoutSubview()。因为它会在布局更新后更新框架
-
GAVIN - 您显示的代码似乎位于安全区域顶部上方 660 点处的
logo(即远离屏幕顶部) )。所以,暂时忘记你的限制......编辑你的问题并解释(最好用一两张图片)你想要做什么。 -
@DonMag 嗨,我用照片更新了帖子并修复了填充。谢谢。
-
@GAVINALFARO - 有些人通过界面设计过着很好的生活。这不是一个简单的布局元素,使它们在一个屏幕尺寸/分辨率上看起来不错,并期望它“神奇地”在所有这些上看起来都不错。您确实需要首先考虑希望它在不同设备上的外观,然后然后弄清楚您需要哪些约束,需要哪些元素在子视图和/或堆栈视图中“分组”,您希望间距增加/缩小等。
-
@GAVINALFARO - 例如,以下是您屏幕的三种变体:imgur.com/a/lMDWXph ... 没有一个可能正是您想要的,但它希望能帮助您了解您需要投入大量考虑您希望您的 UI 如何在不同设备上显示。
标签: ios swift xcode autolayout