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

currencySelector.text = "foobar"

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


当前回答

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

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

}

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

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

其他回答

斯威夫特5:

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

斯威夫特3:

设置按钮标题:

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

// For highlighted state:
my_btn.setTitle("Button Title2", for: .highlighted)

斯威夫特3

当你做@IBAction时:

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

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

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

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

}

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

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

斯威夫特5.0

// Standard State
myButton.setTitle("Title", for: .normal)