简体   繁体   English

添加约束而无需自动布局

[英]Adding constraints without auto-layout

I am building an app with a modal view containing a UICollectionView and below it a view containing two buttons (validate/cancel). 我正在使用包含UICollectionView的模态视图构建应用程序,并在其下方包含两个按钮(验证/取消)的视图。

The number of rows in my UICollectionView can change depending on the data and don't know it beforehand so I want to add a constraint to always keep my buttons 30px below the collectionView. UICollectionView中的行数可以根据数据而变化,并且事先不知道,因此我想添加一个约束以使我的按钮始终保持在collectionView下30px。

I am not using auto-layout for this as I have some animations which work better without it so I don't know how to programmatically add such constraints. 我没有为此使用自动布局,因为有些动画如果没有它会更好地工作,所以我不知道如何以编程方式添加此类约束。

Does anyone have any idea how to do it? 有谁知道如何做吗?

Many thanks for your help 非常感谢您的帮助

I am not sure about the collection view. 我不确定集合视图。 However, the below works with a standard view and since UICollectionView is a type of UIView, then the code might work with collection view also 但是,以下代码适用于标准视图,并且由于UICollectionView是UIView的一种,因此代码也可能适用于集合视图

NSLayoutConstraint *bottomConstraint=[NSLayoutConstraint constraintWithItem:buttonA attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeBottom multiplier:0.45 constant:0];
    NSLayoutConstraint *widthConstraint=[NSLayoutConstraint constraintWithItem:buttonA attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1 constant:95];
    NSLayoutConstraint *heightConstraint=[NSLayoutConstraint constraintWithItem:buttonA attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1 constant:95];
    NSLayoutConstraint *leftConstraint=[NSLayoutConstraint constraintWithItem:buttonA attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeft multiplier:1 constant:20];
    [self.view addConstraints:@[bottomConstraint,widthConstraint,heightConstraint,leftConstraint]];

The above basically lays out the buttonA relative to the view. 上面基本上列出了相对于视图的buttonA。 However, to use this, the auto layout should be off (as in your case). 但是,要使用此功能,应关闭自动布局(根据您的情况)。

The bottom Constraint says that this constraint is related to button A and will act on its attribute NSLayoutAttributeBottom(bottom side) and the bottom side will be present on exactly 0.45*(Bottom of view). 底部约束表示此约束与按钮A相关,并将作用于其属性NSLayoutAttributeBottom(底部),而底部将恰好位于0.45 *(底部视图)上。

The width constraint specifies that it is related to button A and will act on its width. 宽度约束指定它与按钮A相关,并将作用于其宽度。 The width is not dependent on any other object (toItem is nil) and it will have a constant value of 95. 宽度不依赖于任何其他对象(toItem为nil),并且其常数值为95。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM