问题很简单。我有一个UIButton, currencySelector,我想通过编程改变文本。以下是我所拥有的:

currencySelector.text = "foobar"

Xcode给了我一个错误“Expected Declaration”。我做错了什么,我如何使按钮的文本更改?


当前回答

斯威夫特5:

    let controlStates: Array<UIControl.State> = [.normal, .highlighted, .disabled, .selected, .focused, .application, .reserved]
    for controlState in controlStates {
        button.setTitle(NSLocalizedString("Title", comment: ""), for: controlState)
    }

其他回答

在Xcode中使用swift - 04为按钮设置标题: 首先创建一个名为setTitle的方法,参数title和UIController state如下所示;

func setTitle(_ title : String?, for state : UIControl.State)   {

}

在按钮动作方法中回忆这个方法 像;

yourButtonName.setTitle("String", for: .state)

斯威夫特3

当你做@IBAction时:

@IBAction func btnAction(_ sender: UIButton) {
  sender.setTitle("string goes here", for: .normal)
}

这将发送方设置为UIButton(而不是Any),因此它将btnAction作为一个UIButton

Swift 4.2及以上版本

使用按钮的IBOutlet

btnOutlet.setTitle("New Title", for: .normal)

使用按钮的IBAction

@IBAction func btnAction(_ sender: UIButton) {
  sender.setTitle("New Title", for: .normal)
}

斯威夫特5:

    let controlStates: Array<UIControl.State> = [.normal, .highlighted, .disabled, .selected, .focused, .application, .reserved]
    for controlState in controlStates {
        button.setTitle(NSLocalizedString("Title", comment: ""), for: controlState)
    }

在Swift 3,4,5中:

button.setTitle("Button Title", for: .normal)

否则:

button.setTitle("Button Title", forState: UIControlState.Normal)

还必须为按钮声明@IBOutlet。