简体   繁体   English

如何使用程序约束将两个文本视图堆叠+居中?

[英]How to stack + center two text views using programatic constraints?

I'm trying to achieve a hard coded layout where two text views should be stacked on top of each other and centered in a parent UICollectionViewCell: 我正在尝试实现一种硬编码布局,在该布局中,两个文本视图应相互堆叠,并以父UICollectionViewCell为中心:

----------------------
|                    |
|    This is text    |
|      Also text     |
|                    |
----------------------

Due to various legacy/business reasons, I should be doing this using constraints hard coded in a subclass of UICollectionViewCell. 由于各种遗留/业务原因,我应该使用在UICollectionViewCell的子类中硬编码的约束来执行此操作。 The two text views can vary in length, but should be centered vertically in the parent view, while being on top of one another. 这两个文本视图的长度可以不同,但​​应在父视图中垂直居中,并且彼此重叠。

Is there an easy way to express this in constraints? 有没有一种简单的方法可以在约束条件下表达这一点? I'm a bit new to this type of layout system, so any help is appreciated! 我对这种布局系统有点陌生,因此不胜感激!

The app I am working with uses the Masonry ( https://github.com/SnapKit/Masonry ) library as well, if that makes things easier. 我正在使用的应用程序也使用Masonry( https://github.com/SnapKit/Masonry )库,如果这样会使事情变得更容易的话。

Let's asume that the labels are named textView1 and textView2 . 假设标签分别命名为textView1textView2

What you need is to set a constraint for centering horizontally textView1 to it's superview (the UICollectionViewCell ), then center textView2 with textView1 (you can center to it's superview too) and you will have both centered. 你需要的是设定一个约束的水平居中textView1它是superview (该UICollectionViewCell ),然后中心textView2textView1 (你可以向中心是superview太),你将有两个中心。

For getting it on top of one another, you have to set a constraint for setting textView2 top as the textView1 bottom. 为了使它彼此textView2 ,必须设置一个约束,将textView2 top设置为textView1 bottom。

Never used Masonry, but looks like you need to have these constraints: 从未使用过砌筑,但是看起来您需要具有以下约束:

[textView1 mas_makeConstraints:^(MASConstraintMaker *make) {
    //Center first textView in the superview
    make.centerX.equalTo(superview); 
}];
[textView2 mas_makeConstraints:^(MASConstraintMaker *make) {
    //Center second textView with the first one 
    make.centerX.equalTo(textView1);
    //Set second textView to be below the first one
    make.top.equalTo(textView1.mas_bottom);
}];

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

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