Ios 自动布局编程纵横比设置
我试图添加一个子视图来查看和定义自动布局约束,包括纵横比。但我在运行时看到的纵横比并不是我在约束中定义的。我做错了什么?正如您在代码中看到的,背景视图高度应该是背景视图宽度的0.5,但屏幕截图中的情况并非如此。这是我的密码:Ios 自动布局编程纵横比设置,ios,autolayout,uikit,ios-autolayout,Ios,Autolayout,Uikit,Ios Autolayout,我试图添加一个子视图来查看和定义自动布局约束,包括纵横比。但我在运行时看到的纵横比并不是我在约束中定义的。我做错了什么?正如您在代码中看到的,背景视图高度应该是背景视图宽度的0.5,但屏幕截图中的情况并非如此。这是我的密码: class ViewController: UIViewController { private var backgroundView:UIView? override func viewDidLoad() { super.viewDidLoad() /
class ViewController: UIViewController {
private var backgroundView:UIView?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
view.backgroundColor = UIColor.orange
backgroundView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 100))
backgroundView?.backgroundColor = UIColor.black.withAlphaComponent(1.0)
backgroundView?.layer.borderColor = UIColor.white.cgColor
backgroundView?.layer.borderWidth = 1.5
backgroundView?.layer.cornerRadius = 4
backgroundView?.clipsToBounds = true
backgroundView?.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(backgroundView!)
backgroundView?.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 1.0).isActive = true
backgroundView?.heightAnchor.constraint(equalTo: backgroundView!.widthAnchor, multiplier: 0.5).isActive = true
backgroundView?.centerXAnchor.constraint(equalTo: view!.centerXAnchor, constant: 0).isActive = true
backgroundView?.topAnchor.constraint(equalTo: view!.topAnchor, constant: 4).isActive = true
}
}
以下是截图:
尝试更改高度约束以设置:
backgroundView?.heightAnchor.constraint(equalTo: view!.heightAnchor, multiplier: 0.5).isActive = true
NB:您得到的正是您想要的结果。它的高度是它宽度的一半。屏幕截图没有问题。“背景视图高度应为背景视图宽度的0.5”
您的屏幕截图大小为1334 x 750
您的backgroundView
(包括边框)是1334 x 667
1334*0.5==667
所以,你得到的正是你想要的 显示用户界面的图像以获得更多理解。为什么在使用自动布局时要设置框架?请尝试-将高度约束更改为:
.heightAnchor.constraint(equalTo:view.widthAnchor,乘数:0.5)
@LalKrishna heightAnchor采用尺寸,常量和乘数作为参数或常量。您的问题仍然缺少纯信息。你想要什么???问题是什么?请清除它。请重新阅读代码,它被设置为宽度锚定,而不是高度锚定。在前一行代码中已经设置了宽度锚。我看到了。但在评论中,你问为什么黑色视图的高度不等于视图高度除以2?,所以你需要视图的高度应该是自身高度的一半,不是吗?这是你的要求吗?我的要求是代码有什么问题?为什么这两行没有设置纵横比。您正在将背景视图的高度设置为backgroundView.width/2.0
,为什么屏幕截图中没有出现这种情况?