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

currencySelector.text = "foobar"

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


当前回答

斯威夫特3:

设置按钮标题:

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

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

其他回答

Swift 4.2及以上版本

使用按钮的IBOutlet

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

使用按钮的IBAction

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

斯威夫特5.0

// Standard State
myButton.setTitle("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)
    }

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

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

}

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

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

斯威夫特3

let button: UIButton = UIButton()
button.frame = CGRect.init(x: view.frame.width/2, y: view.frame.height/2, width: 100, height: 100)
button.setTitle(“Title Button”, for: .normal)