首页 > 解决方案 > UIButton.setTitle 没有将 UIButton.titleLabel.text 设置为空字符串

问题描述

这不是问题,但我发现UIButton.setTitle没有设置UIButton.titleLabel.text"". 所以如果你想设置UIButton.titleLabel.text""应该使用UIButton.titleLabel.text = ""after UIButton.setTitle("", for: .normal)

在操场上它看起来像:

import UIKit

let button = UIButton()
button.setTitle("1", for: .normal)
print(button.titleLabel?.text ?? "no value")
//print 1
button.setTitle("2", for: .normal)
print(button.titleLabel?.text ?? "no value")
//print 2
button.setTitle("3", for: .normal)
print(button.titleLabel?.text ?? "no value")
//print 3
button.setTitle("", for: .normal)
print(button.titleLabel?.text ?? "no value")
//print 3 not ""
button.titleLabel?.text = ""
print(button.titleLabel?.text ?? "no value")
//print ""

但当然button.titleLabel?.text = ""只有在button.setTitle("", for: .normal)

button.setTitle("3", for: .normal)
button.titleLabel?.text = ""
print(button.titleLabel?.text ?? "no value")
//print 3

我不明白为什么会这样。也许有人可以解释为什么?

标签: iosswiftuibutton

解决方案


您可以看到以下关于按钮标题集的苹果描述。见红色标记的矩形。

发件人是 UIButton 的实例

在此处输入图像描述

根据苹果文档:

要设置标签的实际文本,请使用 setTitle(_:for:)。

button.titleLabel.text 不允许您设置文本。

我希望这能帮到您。


推荐阅读