如何以编程方式为容器视图设置自适应约束

问题描述 投票:0回答:1

注意:现在我都以编程方式设置约束和故事板约束。

  1. 问题一:

如果我保持编程和故事板约束,我在我的故事板中得到错误但应用程序工作正常(我用一些程序设计替换了一些故事板约束)。但我能这样做吗?苹果会接受吗?

如果不

  1. 问题二:

我有一个ViewController,我放置了两个容器视图,每个视图都有不同的尺寸,以创建一种侧面菜单。我有一个像屏幕一样大的大屏幕和一个与屏幕一样长但屏幕宽一半的小屏幕。起初我在storyboard中添加了我的约束,但现在我意识到我需要以编程方式设置它们以实现我需要的东西。我需要从故事板转换为代码的约束

大容器375x667:

  • 尾随空间到superView(或者其右侧适应每个设备的东西,我想superview应该可以正常工作);
  • 宽度和高度等于视图;
  • 前导空间到小容器视图(0)。

小型集装箱240x667

  • 宽度等于240;
  • 高度等于大容器的高度;
  • 跟踪大容器的空间(如果我们已经设置了大容器的前导空间,则无需再次添加此容器);
  • 对齐导致安全区域等于-240。

这是我已经完成的(正确的部分):

func containerViewsConstraints() {
 containerView1.translatesAutoresizingMaskIntoConstraints = false

        containerView1.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
        containerView1.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true


        containerView2.translatesAutoresizingMaskIntoConstraints = false
        containerView2.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
        containerView2.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
}

这是我尝试过的(不确定是否正确):

containerView2.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
        containerView2.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true

    containerView2.widthAnchor.isEqual(view.widthAnchor)
        containerView2.heightAnchor.isEqual(view.heightAnchor)

        containerView1.widthAnchor.constraint(equalToConstant: 240)
        containerView1.heightAnchor.isEqual(view.heightAnchor)
swift uiview constraints uicontainerview
1个回答
0
投票

你需要

bigView.backgroundColor = .red
smallView.backgroundColor = .green 
bigView.translatesAutoresizingMaskIntoConstraints = false
smallView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(bigView)
view.addSubview(smallView)
NSLayoutConstraint.activate([

    bigView.topAnchor.constraint(equalTo: view.topAnchor),
    bigView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
    bigView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
    bigView.trailingAnchor.constraint(equalTo: view.trailingAnchor),

    smallView.topAnchor.constraint(equalTo: view.topAnchor),
    smallView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
    smallView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
    smallView.widthAnchor.constraint(equalTo: view.widthAnchor,multiplier:0.5)

])
© www.soinside.com 2019 - 2024. All rights reserved.