ios 以编程方式更新高度约束

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30060373/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 05:54:26  来源:igfitidea点击:

Update height constraint programmatically

iosobjective-cswiftautolayoutnslayoutconstraint

提问by Tapas Pal

I am new in auto layout. I have done all of my project from xib file, but now I faced a problem where I have to update an view's height programmatically. I have tried below but now working.

我是自动布局的新手。我已经从 xib 文件完成了我的所有项目,但现在我遇到了一个问题,我必须以编程方式更新视图的高度。我在下面尝试过,但现在正在工作。

[[self view] addConstraint:[NSLayoutConstraint constraintWithItem:loginContainer attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0f constant:loginFrame.size.height]];

In console it's shows

在控制台中显示

Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints) 
(
    "<NSLayoutConstraint:0x78724530 V:[UIView:0x790cdfb0(170)]>",
    "<NSLayoutConstraint:0x787da210 V:[UIView:0x790cdfb0(400)]>"
)

Will attempt to recover by breaking constraint 
<NSLayoutConstraint:0x78724530 V:[UIView:0x790cdfb0(170)]>

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.

回答by Dave Paul

Instead of adding a new constraint, you need to modify the constant on your existing constraint.

您需要修改现有约束上的常量,而不是添加新约束。

Use an IBOutlet to connect to your constraint in Interface Builder:

使用 IBOutlet 连接到 Interface Builder 中的约束:

@property (nonatomic, weak) NSLayoutConstraint *heightConstraint;

Then, when you need to set it programmatically, simply set the constant property on the constraint:

然后,当您需要以编程方式设置它时,只需在约束上设置常量属性:

heightConstraint.constant = 100;

OR

或者

If you can't access the nib in Interface Builder, find the constraint in code:

如果在 Interface Builder 中无法访问笔尖,请在代码中找到约束:

NSLayoutConstraint *heightConstraint;
for (NSLayoutConstraint *constraint in myView.constraints) {
    if (constraint.firstAttribute == NSLayoutAttributeHeight) {
        heightConstraint = constraint;
        break;
    }
}
heightConstraint.constant = 100;

And in Swift:

在 Swift 中:

if let constraint = (myView.constraints.filter{
self.heightConstraint.constant = 300;
[self.view updateConstraints];
.firstAttribute == .width}.first) { constraint.constant = 100.0 }

回答by Hamza

To get a reference of your height constraints : Click + Ctrl in the constraint and drag and drop in your class file :

要获取高度约束的参考:在约束中单击 + Ctrl 并拖放到类文件中:

enter image description here

在此处输入图片说明

To update constraint value :

更新约束值:

extension UIView {    

    func updateConstraint(attribute: NSLayoutAttribute, constant: CGFloat) -> Void {
        if let constraint = (self.constraints.filter{
// to update height constant
testView.updateConstraint(attribute: NSLayoutAttribute.height, constant: 20.0)


// to update width constant
testView.updateConstraint(attribute: NSLayoutAttribute.width, constant: 20.0)
.firstAttribute == attribute}.first) { constraint.constant = constant self.layoutIfNeeded() } } }

回答by Krunal

A more flexible way using this swift extension:

使用此 swift 扩展的更灵活的方法:

[[NSBundle mainBundle] loadNibNamed:@"NibView" owner:self options:nil];

How to use this view extension to update constant value of existing constraints:

如何使用此视图扩展更新现有约束的常量值:

nibView.translatesAutoresizingMaskIntoConstraints = NO;

回答by fdiaz

Let's call your view nibView. So, you are trying to load that view in a view controller, so first, in your view controller, you need to load it as you are doing it with:

让我们将您的视图称为nibView。因此,您正在尝试在视图控制器中加载该视图,因此首先,在您的视图控制器中,您需要按照以下方式加载它:

    NSLayoutConstraint *heightConstraint = [NSLayoutConstraint constraintWithItem:nibView
                                                                                  attribute:NSLayoutAttributeHeight
                                                                                  relatedBy:NSLayoutRelationEqual
                                                                                     toItem:nil
                                                                                  attribute:NSLayoutAttributeNotAnAttribute
                                                                                 multiplier:1.0
                                                                                   constant:yourValue];

Then you need to tell the nibView that you don't need it to transform the autoresizing masks into constraints by doing

然后你需要告诉 nibView 你不需要它通过执行将自动调整大小掩码转换为约束

[self.view addConstraint:heightConstraint];

Then, you can add your constraints

然后,您可以添加约束

import UIKit

class AnimateHeightConstraintViewController: UIViewController {
    var flowHeightConstraint: NSLayoutConstraint?

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white

        view.addSubview(button)
        button.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        button.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
        button.widthAnchor.constraint(equalToConstant: 100).isActive = true
        flowHeightConstraint = button.heightAnchor.constraint(equalToConstant: 30)
        flowHeightConstraint?.isActive = true
    }

    @objc func animateButtonTapped() {
        UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.5, options: .curveEaseOut, animations: {
            self.flowHeightConstraint?.constant = 100
            self.view.layoutIfNeeded()
        }, completion: nil)
    }

    lazy var button: UIButton = {
       let button = UIButton()
        button.translatesAutoresizingMaskIntoConstraints = false
        button.backgroundColor = .green
        button.addTarget(self, action: #selector(animateButtonTapped), for: .touchUpInside)
        return button
    }()
}

And finally just add it to your view constraints:

最后将其添加到您的视图约束中:

##代码##

You probably would need to add a width constraint also.

您可能还需要添加宽度约束。

回答by moraei

Swift 4.2

斯威夫特 4.2

Using auto layout and animation to increase height of button

使用自动布局和动画来增加按钮的高度

I don't use story board. all things in code.

我不使用故事板。代码中的所有内容。

##代码##

and result is like this:

结果是这样的:

enter image description here

在此处输入图片说明