以编程方式快速更改UIButton的文本

roc*_*101 207 xcode uibutton ios swift

简单问题在这里.我有一个UIButton,currencySelector,我想以编程方式更改文本.这就是我所拥有的:

currencySelector.text = "foobar"
Run Code Online (Sandbox Code Playgroud)

Xcode给出了错误"预期声明".我做错了什么,如何让按钮的文字改变?

Gal*_*rom 549

在Swift 3中:

button.setTitle("Button Title",for: .normal)
Run Code Online (Sandbox Code Playgroud)

除此以外:

button.setTitle("Button Title", forState: UIControlState.Normal)
Run Code Online (Sandbox Code Playgroud)

  • 你可以省略`UIControlState`.例如`forState:.Normal` (30认同)
  • Swift3现在是`.normal`注意小写 (11认同)
  • Swift3将`forState`改为`for` (6认同)
  • 对于swift 4也是`button.setTitle("Button Title",for:.normal)`working!,谢谢 (5认同)

Ben*_*rix 71

只是对SwiftiOS编程新手的澄清.下面的代码行:

button.setTitle("myTitle", forState: UIControlState.Normal)
Run Code Online (Sandbox Code Playgroud)

只适用于IBOutlets,而不是IBActions.

所以,如果您的应用使用一个按钮的功能,以执行一些代码,说播放音乐,并希望标题从改变PlayPause基于一个切换变量,您还需要创建一个IBOutlet该按钮.

如果你试图使用button.setTitle反对,IBAction你将收到一个错误.一旦你知道它就很明显,但对于新手(我们都是),这是一个有用的提示.

  • 这个答案毫无意义.动作的"发送者"将是按钮.你可以将任何你想要的东西应用于`sender`.你不需要一个插座来做这件事. (8认同)
  • 这是IOS中的一种模式,我花了一段时间才发现。除非创建 IBOutlet,否则您无权访问 UI 项的属性。如果您曾经尝试更改 UI 的属性但无法访问它,请确保您同时拥有正在运行某些代码的 IBAction 和提供对这些属性的访问权限的 IBOutlet。 (2认同)
  • 本迪克斯的回答和他的评论都不正确.他们是完全错的. (2认同)

Dmi*_*try 11

斯威夫特4:

    for state: UIControlState in [.normal, .highlighted, .disabled, .selected, .focused, .application, .reserved] {
        button.setTitle(NSLocalizedString("Title", comment: ""), for: state)
    }
Run Code Online (Sandbox Code Playgroud)


Bha*_*ani 8

斯威夫特3:

设置按钮标题:

//for normal state:
my_btn.setTitle("Button Title", for: .normal)

// For highlighted state:
my_btn.setTitle("Button Title2", for: .highlighted)
Run Code Online (Sandbox Code Playgroud)


Tyl*_*utt 7

Swift 3.0

// Standard State
myButton.setTitle("Title", for: .normal)
Run Code Online (Sandbox Code Playgroud)


Chr*_*lot 6

归属时更改标题有些不同:

我只是遇到一个问题:如果您的UIButton带有属性标题,则必须使用:

my_btn.setAttributedTitle(NSAttributedString(string: my_title), for: my_state)
Run Code Online (Sandbox Code Playgroud)

根据Apple SetTitle Doc

如果同时为按钮设置标题和属性标题,则该按钮比该按钮更喜欢使用属性标题。

我有一个归属的标题,我试图对其设置setTitle,但没有效果...