如何在iOS中以编程方式设置纵横比约束?

时间:2022-08-27 10:46:14

I have used auto layout for my view controllers. I have set the V and H positions in constraints, but I want to know how can I increase my button size when it changes to 5s, 6 and 6 Plus. This is the way I added constraints for the login button:

我的视图控制器使用了自动布局。我已经在约束条件下设置了V和H的位置,但是我想知道当它变成5s、6和6 Plus时,我如何增加按钮的大小。这是我为登录按钮添加的约束:

NSArray *btncon_V=[NSLayoutConstraint constraintsWithVisualFormat:@"V:[btnLogin(40)]" options:0 metrics:nil views:viewsDictionary];
[btnLogin addConstraints:btncon_V];

NSArray *btncon_POS_H=[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-100-[btnLogin]-100-|" options:0 metrics:nil views:viewsDictionary];
[self.view addConstraints:btncon_POS_H];


NSArray *btncon_POS_V=[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-70-[Title]-130-[lblFirst]-0-[lblSecond]-20-[textusername]-10-[txtpassword]-10-[btnLogin]" options:0 metrics:nil views:viewsDictionary];

[self.view addConstraints:btncon_POS_V];

But my problem is that while it manages the left and right side gap, it's getting stretched in iPhone 6 and 6 Plus since the height is fixed. How can I increase the size according to the screen size? I think this might be the aspect ratio, but how can I set the aspect ratio constraint in code?

但我的问题是,当它管理左右两边的间隙时,它在iPhone 6和iPhone 6 Plus中被拉伸了,因为高度是固定的。如何根据屏幕大小增加尺寸?我认为这可能是纵横比,但是如何在代码中设置纵横比约束呢?

5 个解决方案

#1


54  

Like this. Try once.

像这样。尝试一次。

[self.yourview setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.yourview addConstraint:[NSLayoutConstraint
                                  constraintWithItem:self.yourview
                                  attribute:NSLayoutAttributeHeight
                                  relatedBy:NSLayoutRelationEqual
                                  toItem:self.yourview
                                  attribute:NSLayoutAttributeWidth
                                  multiplier:(self.yourview.frame.size.height / self.yourview.frame.size.width)
                                  constant:0]];

or in the place of (self.yourview.frame.size.height / self.yourview.frame.size.width) you can use any float value. Thanks.

或者在(self.yourview.frame.size.height / self.yourview.frame.size.width)的位置,您可以使用任何浮点值。谢谢。

Swift 3.0 -

斯威夫特3.0 -

self.yourview!.translatesAutoresizingMaskIntoConstraints = false
self.yourview!.addConstraint(NSLayoutConstraint(item: self.yourview!,
                                          attribute: NSLayoutAttribute.height,
                                          relatedBy: NSLayoutRelation.equal,
                                          toItem: self.yourview!,
                                          attribute: NSLayoutAttribute.width,
                                          multiplier: self.yourview.frame.size.height / self.yourview.frame.size.width,
                                          constant: 0))

#2


13  

Layout Anchors is the most convenient way to set constraints programmatically.

布局锚是编程设置约束的最方便的方式。

Say you want to set 5:1 aspect ratio for your button then you should use:

如果你想为你的按钮设置5:1的纵横比,那么你应该使用:

button.heightAnchor.constraint(equalTo: button.widthAnchor, multiplier: 1.0/5.0).isActive = true

Here's the full code:

完整的代码:

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let button = UIButton(type: .custom)
        button.setTitle("Login", for: .normal)
        button.backgroundColor = UIColor.darkGray

        self.view.addSubview(button)

        button.translatesAutoresizingMaskIntoConstraints = false

        let margins = view.layoutMarginsGuide

        button.leadingAnchor.constraint(equalTo: margins.leadingAnchor, constant: 20.0).isActive = true
        button.trailingAnchor.constraint(equalTo: margins.trailingAnchor, constant: -20.0).isActive = true
        button.bottomAnchor.constraint(equalTo: margins.bottomAnchor, constant: -20.0).isActive = true
        button.heightAnchor.constraint(equalTo: button.widthAnchor, multiplier: 1.0/5.0).isActive = true
    }

}

Here're results achieved with code written above. You can see that button keeps its 5:1 aspect ratio across various devices:

下面是上面编写的代码实现的结果。你可以看到按钮在不同设备上保持5:1的纵横比:

如何在iOS中以编程方式设置纵横比约束?

#3


9  

Swift 3:

斯威夫特3:

yourView.addConstraint(NSLayoutConstraint(item: yourView,
                                          attribute: .height,
                                          relatedBy: .equal,
                                          toItem: yourView,
                                          attribute: .width,
                                          multiplier: 9.0 / 16.0,
                                          constant: 0))

#4


7  

You can set "Height constraint" at Design-time in Interface Builder. Just check '"Remove at build time", and it removes when App will running.

您可以在接口构建器的设计时设置“高度约束”。只要检查“在构建时删除”,它就会在程序运行时删除。

如何在iOS中以编程方式设置纵横比约束? After that you can add "Aspect Ratio" constraint, for example, in viewDidLoad method.

之后,您可以添加“纵横比”约束,例如,在viewDidLoad方法中。

In Xamain.iOS for "16:9" it's looks like this:

在Xamain。iOS对于“16:9”是这样的:

    this.ImageOfTheDay.AddConstraint(NSLayoutConstraint.Create(
            this.ImageOfTheDay,
            NSLayoutAttribute.Height,
            NSLayoutRelation.Equal,
            this.ImageOfTheDay,
            NSLayoutAttribute.Width,
            9.0f / 16.0f,
            0));

Or, as Mahesh Agrawal said:

或者,正如马赫格拉沃尔所说:

    [self.ImageOfTheDay addConstraint:[NSLayoutConstraint
                              constraintWithItem:self.ImageOfTheDay
                              attribute:NSLayoutAttributeHeight
                              relatedBy:NSLayoutRelationEqual
                              toItem:self.ImageOfTheDay
                              attribute:NSLayoutAttributeWidth
                              multiplier:(9.0f / 16.0f)
                              constant:0]];

#5


2  

I have try all answers above but didn't work, and this is my solution with swift 3:

以上所有答案我都试过了,但是没有成功,这是我用swift 3的解决方案:

let newConstraint = NSLayoutConstraint(item: yourView, attribute: .width, relatedBy: .equal, toItem: yourView, attribute: .height, multiplier: 560.0/315.0, constant: 0)
yourView.addConstraint(newConstraint)
NSLayoutConstraint.activate([newConstraint])  
NSLayoutConstraint.deactivate(yourView.constraints)
yourView.layoutIfNeeded()

#1


54  

Like this. Try once.

像这样。尝试一次。

[self.yourview setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.yourview addConstraint:[NSLayoutConstraint
                                  constraintWithItem:self.yourview
                                  attribute:NSLayoutAttributeHeight
                                  relatedBy:NSLayoutRelationEqual
                                  toItem:self.yourview
                                  attribute:NSLayoutAttributeWidth
                                  multiplier:(self.yourview.frame.size.height / self.yourview.frame.size.width)
                                  constant:0]];

or in the place of (self.yourview.frame.size.height / self.yourview.frame.size.width) you can use any float value. Thanks.

或者在(self.yourview.frame.size.height / self.yourview.frame.size.width)的位置,您可以使用任何浮点值。谢谢。

Swift 3.0 -

斯威夫特3.0 -

self.yourview!.translatesAutoresizingMaskIntoConstraints = false
self.yourview!.addConstraint(NSLayoutConstraint(item: self.yourview!,
                                          attribute: NSLayoutAttribute.height,
                                          relatedBy: NSLayoutRelation.equal,
                                          toItem: self.yourview!,
                                          attribute: NSLayoutAttribute.width,
                                          multiplier: self.yourview.frame.size.height / self.yourview.frame.size.width,
                                          constant: 0))

#2


13  

Layout Anchors is the most convenient way to set constraints programmatically.

布局锚是编程设置约束的最方便的方式。

Say you want to set 5:1 aspect ratio for your button then you should use:

如果你想为你的按钮设置5:1的纵横比,那么你应该使用:

button.heightAnchor.constraint(equalTo: button.widthAnchor, multiplier: 1.0/5.0).isActive = true

Here's the full code:

完整的代码:

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let button = UIButton(type: .custom)
        button.setTitle("Login", for: .normal)
        button.backgroundColor = UIColor.darkGray

        self.view.addSubview(button)

        button.translatesAutoresizingMaskIntoConstraints = false

        let margins = view.layoutMarginsGuide

        button.leadingAnchor.constraint(equalTo: margins.leadingAnchor, constant: 20.0).isActive = true
        button.trailingAnchor.constraint(equalTo: margins.trailingAnchor, constant: -20.0).isActive = true
        button.bottomAnchor.constraint(equalTo: margins.bottomAnchor, constant: -20.0).isActive = true
        button.heightAnchor.constraint(equalTo: button.widthAnchor, multiplier: 1.0/5.0).isActive = true
    }

}

Here're results achieved with code written above. You can see that button keeps its 5:1 aspect ratio across various devices:

下面是上面编写的代码实现的结果。你可以看到按钮在不同设备上保持5:1的纵横比:

如何在iOS中以编程方式设置纵横比约束?

#3


9  

Swift 3:

斯威夫特3:

yourView.addConstraint(NSLayoutConstraint(item: yourView,
                                          attribute: .height,
                                          relatedBy: .equal,
                                          toItem: yourView,
                                          attribute: .width,
                                          multiplier: 9.0 / 16.0,
                                          constant: 0))

#4


7  

You can set "Height constraint" at Design-time in Interface Builder. Just check '"Remove at build time", and it removes when App will running.

您可以在接口构建器的设计时设置“高度约束”。只要检查“在构建时删除”,它就会在程序运行时删除。

如何在iOS中以编程方式设置纵横比约束? After that you can add "Aspect Ratio" constraint, for example, in viewDidLoad method.

之后,您可以添加“纵横比”约束,例如,在viewDidLoad方法中。

In Xamain.iOS for "16:9" it's looks like this:

在Xamain。iOS对于“16:9”是这样的:

    this.ImageOfTheDay.AddConstraint(NSLayoutConstraint.Create(
            this.ImageOfTheDay,
            NSLayoutAttribute.Height,
            NSLayoutRelation.Equal,
            this.ImageOfTheDay,
            NSLayoutAttribute.Width,
            9.0f / 16.0f,
            0));

Or, as Mahesh Agrawal said:

或者,正如马赫格拉沃尔所说:

    [self.ImageOfTheDay addConstraint:[NSLayoutConstraint
                              constraintWithItem:self.ImageOfTheDay
                              attribute:NSLayoutAttributeHeight
                              relatedBy:NSLayoutRelationEqual
                              toItem:self.ImageOfTheDay
                              attribute:NSLayoutAttributeWidth
                              multiplier:(9.0f / 16.0f)
                              constant:0]];

#5


2  

I have try all answers above but didn't work, and this is my solution with swift 3:

以上所有答案我都试过了,但是没有成功,这是我用swift 3的解决方案:

let newConstraint = NSLayoutConstraint(item: yourView, attribute: .width, relatedBy: .equal, toItem: yourView, attribute: .height, multiplier: 560.0/315.0, constant: 0)
yourView.addConstraint(newConstraint)
NSLayoutConstraint.activate([newConstraint])  
NSLayoutConstraint.deactivate(yourView.constraints)
yourView.layoutIfNeeded()