UIButton 标题不显示

Posted

技术标签:

【中文标题】UIButton 标题不显示【英文标题】:UIButton title not displaying 【发布时间】:2014-06-03 15:51:40 【问题描述】:

我刚开始使用 Swift 进行开发。

我动态创建了一个 UIButton 并将其添加到视图中。 我的问题是视图没有显示按钮。

我的代码:

var button:UIButton = UIButton();
button.frame = CGRect(x: 100, y: 250, width: 100, height: 50);
button.setTitle("Midhun", forState: UIControlState.Normal);
self.view.addSubview(button);

然后我将图像添加到按钮,然后显示:

button.setImage(UIImage(named: "step_first.jpg"), forState: UIControlState.Normal);

我无法弄清楚发生了什么。请帮忙

【问题讨论】:

我之前也遇到过这个问题,默认情况下它是白色的。 【参考方案1】:

如果您继承 UIButton 并覆盖其 layoutSubviews(),请确保在内部调用 super.layoutSubviews()

【讨论】:

【参考方案2】:

对我来说,问题在于我没有使用 setter 方法。

我在做notificationsButton.titleLabel?.text = "x" 而不是notificationsButton.setTitle("x", forState: UIControlState.Normal)

【讨论】:

但是你需要更改标题的文本颜色noticesButton.setTitleColor(UIColor.blackColor(), forState: .Normal) 或者按钮的背景颜色noticesButton.backgroundColor = UIColor.blackColor() Swift 5 : myButton.setTitle("myButtonText", for: .normal)【参考方案3】:

我确实发现了这个问题。

在 Swift 中,UIButton 的标题是白色的。

我更改了父视图的背景颜色,现在它正在显示。

self.view.backgroundColor = UIColor.black

【讨论】:

这是一些有价值的信息,默认为白色,谢谢 起初,当我复制/粘贴您的代码时,我看到了按钮,但后来我意识到文本是白色的,很高兴知道这些属性需要正确设置。可能不会影响大多数拥有非常自定义 UIElements 的人。 或者,您可以使用 setter .setTitleColor文本颜色 更改为黑色

以上是关于UIButton 标题不显示的主要内容,如果未能解决你的问题,请参考以下文章

iOS:UIButton 不显示

带有动画图像的 UIButton 不显示

以编程方式将 UIButton 添加到 UITableView 但按钮不显示

UIButton 在 iOS 9.3 上不显示

具有突出显示不透明度和动画的圆形 UIButton

为啥从自定义 UIView 向 UIButton 添加子视图不显示添加的子视图?