问题很简单。我有一个UIButton, currencySelector,我想通过编程改变文本。以下是我所拥有的:
currencySelector.text = "foobar"
Xcode给了我一个错误“Expected Declaration”。我做错了什么,我如何使按钮的文本更改?
问题很简单。我有一个UIButton, currencySelector,我想通过编程改变文本。以下是我所拥有的:
currencySelector.text = "foobar"
Xcode给了我一个错误“Expected Declaration”。我做错了什么,我如何使按钮的文本更改?
当前回答
截至2021年12月12日- Swift版本5.5.1^假设你已经有一个IBOutlet链接到你的按钮在正常状态。
yourButton.setTitle("Title of your button", for: .normal)
其他回答
当有属性时改变标题有点不同:
我遇到了一个问题:如果你有一个带有标题的UIButton,你必须使用:
my_btn.setAttributedTitle(NSAttributedString(string: my_title), for: my_state)
根据Apple SetTitle Doc:
如果同时为按钮设置标题和带属性标题,则按钮更倾向于使用带属性标题。
我有一个带属性的标题,我试图在它上设置标题,没有效果…
斯威夫特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。
截至2021年12月12日- Swift版本5.5.1^假设你已经有一个IBOutlet链接到你的按钮在正常状态。
yourButton.setTitle("Title of your button", for: .normal)
在Xcode中使用swift - 04为按钮设置标题: 首先创建一个名为setTitle的方法,参数title和UIController state如下所示;
func setTitle(_ title : String?, for state : UIControl.State) {
}
在按钮动作方法中回忆这个方法 像;
yourButtonName.setTitle("String", for: .state)