Adding constraints without auto-layout

点点圈 提交于 2019-12-12 05:46:26

问题


I am building an app with a modal view containing a UICollectionView and below it a view containing two buttons (validate/cancel).

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.

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


回答1:


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

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. 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).

The width constraint specifies that it is related to button A and will act on its width. The width is not dependent on any other object (toItem is nil) and it will have a constant value of 95.



来源:https://stackoverflow.com/questions/18148061/adding-constraints-without-auto-layout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!