简体   繁体   English

如何有条件地使图像在StackView中居中

[英]How to center image in StackView conditionally

I have a StackView containing a UIImageView and a UILabel. 我有一个包含UIImageView和UILabel的StackView。 Sometimes the UILabel contains a quotation and sometimes it does not. 有时,UILabel包含引号,有时则不包含引号。 When it does I want the UIImageView to be 40% of the device width - I have that part working. 当它完成时,我希望UIImageView是设备宽度的40%-我可以用那部分工作。 When it does not I want the UIImageView still to be the same width, just centered horizontally. 如果不是,我希望UIImageView仍然是相同的宽度,只是水平居中。 What's the easiest way to achieve this? 最简单的方法是什么? StackView

StackView设置

It seems that UIStackView is not what you really need there, but rather simple UIView , which is centered vertically in the parent view, and contains UIImageView and UILabel , and then set imageView.trailing equal to label.leading , plus label.sizeToFit() . 看来,UIStackView是不是你真正需要的存在,而是简单UIView ,这是在父视图垂直居中,并且包含UIImageViewUILabel ,然后设置imageView.trailing等于label.leading ,加上label.sizeToFit()

But if you want to stick to your design, what you could do is programmatically set UIStackView axes. 但是,如果您想坚持自己的设计,则可以通过编程方式设置UIStackView轴。 For instance, set stack view in IB like: 例如,在IB中设置堆栈视图,如下所示:

UIStackView IB setting UIStackView IB设置

and then in code in viewDidLoad() method: 然后在viewDidLoad()方法的代码中:

if label.text == "" {
    stackView.axis = .vertical
} else {
    stackView.axis = .horizontal
} 

also with label.sizeToFit() . 也带有label.sizeToFit()

That should do the trick. 这应该够了吧。

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

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