简体   繁体   English

iOS Swift UIImageView 纵横比未隐藏

[英]iOS Swift UIImageView with aspect ratio not getting hide

In my application I want to show customise buttons like:在我的应用程序中,我想显示自定义按钮,例如:

  • Title Only Button仅标题按钮
  • Button with Image + Title带有图像 + 标题的按钮
  • Image Only Button仅图像按钮

在此处输入图像描述 在此处输入图像描述 在此处输入图像描述

To create a such button I have taken a UIView and Under That I have added UIImageView with aspect ratio of 24:48 and UILable .要创建这样的按钮,我采用了UIView并在其下添加了UIImageViewaspect ratio为 24:48 和UILable

For button Type Image + Title everything works fine but for Title only button my UIIlmageView is not getting hidden ie even I have added对于按钮类型图像 + 标题,一切正常,但对于仅标题按钮,我的UIIlmageView没有被隐藏,即即使我已经添加

        leftImageviewWidthConstaraint.constant = 0

        leftImageviewWidthConstaraint.isActive = false 

what else I am missing.我还缺少什么。 Please suggest.请建议。

When you do leftImageviewWidthConstaraint.isActive = false you turn off the constraint, so natural content size might cause it to still be visible..当您执行leftImageviewWidthConstaraint.isActive = false时,您会关闭约束,因此自然内容大小可能会导致它仍然可见..

So just do所以就这样做

leftImageviewWidthConstaraint.constant = 0 to change the value and DONT disable it after. leftImageviewWidthConstaraint.constant = 0更改值并在之后禁用它。

You can also try a self.layoutIfNeeded() after adjusting constraints;您也可以在调整约束后尝试self.layoutIfNeeded() on rare occasions that helps在极少数情况下会有所帮助

What I would do is add the UIImageView and the UILabel in a horizontal UIStackView with Fill Proportionally distribution.我要做的是将 UIImageView 和 UILabel 添加到水平 UIStackView 中,并按比例分布。 This way if you give the UIImageView a fixed size, the UILabel will get the rest of the space and if you HIDE the UIImageView, the UILabel will get the whole space of the StackView.这样,如果你给 UIImageView 一个固定大小,UILabel 将获得空间的 rest,如果你隐藏 UIImageView,UILabel 将获得整个空间的 StackView。 Same thing if you hide the UILabel.如果你隐藏 UILabel,同样的事情。

Hope it helps!希望能帮助到你!

Make sure that the leading or left constraint of the label is connected to the trailing or right constraint of the image view and not to the left side of the container view.确保 label 的前导约束连接到图像视图的尾随约束,而不是容器视图的左侧。 By calling leftImageviewWidthConstaraint.constant = 0 it should work.通过调用leftImageviewWidthConstaraint.constant = 0它应该可以工作。 And don't deactivate the constraint, you might have crashes or other UI issues.并且不要停用约束,您可能会遇到崩溃或其他 UI 问题。 I just gave it a try and it works for me:我只是试了一下,它对我有用:

在此处输入图像描述

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

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