简体   繁体   English

如何动态地将动态大小的UIButtons插入UIStackView?

[英]How to insert UIButtons of Dynamic size into a UIStackView dynamically?

This is working great: 这很有用:

                let label = UILabel()
                label.text = VARIABLE_LENGTH_STRING
                stackView?.addArrangedSubview(label)

but this does not work 但这不起作用

                let button = UIButton()
                button.setTitle(VARIABLE_LENGTH_STRING, for: .normal)
                stackView?.addArrangedSubview(button)

Nothing displays! 什么都没有显示! any idea why? 任何想法为什么? I'd expect labels to behave pretty simularly to buttons... 我希望标签在按钮上表现得非常相似......

Thanks for your help! 谢谢你的帮助!

The problem is that by default - a new UIButton() has white text and a white background --- grrrr! 问题是默认情况下 - 新的UIButton()有白色文本和白色背景--- grrrr!

i fixed this by doing: 我做了这样做:

button.setTitleColor(.blue, for: .normal)

尝试在设置按钮标题后在代码中添加以下行,

 button.sizeToFit()

首先检查“VARIABLE_LENGTH_STRING”中是否有任何值,如果它有空字符串,则不会显示任何内容并给出按钮框架大小,这样如果没有文本按钮,高度宽度将是特定的,并且默认情况下更改按钮背景颜色还有一个很明显所以你只会通过改变背景颜色和框架看到屏幕上的按钮内容你将在屏幕上看到它没有内容显示的事件:)。

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

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