在 Swift 3、4、5 中:
button.setTitle("Button Title", for: .normal)
否则:
button.setTitle("Button Title", forState: UIControlState.Normal)
还必须为 button
声明一个 @IBOutlet
。
只是对 Swift 和 iOS 编程新手的澄清。下面的代码行:
button.setTitle("myTitle", forState: UIControlState.Normal)
仅适用于 IBOutlets
,不适用于 IBActions
。
因此,如果您的应用程序使用按钮作为函数来执行某些代码,例如播放音乐,并且您想根据切换变量将标题从 Play
更改为 Pause
,您还需要创建一个 {3 } 为那个按钮。
如果您尝试对 IBAction
使用 button.setTitle
,则会收到错误消息。一旦你知道它就很明显了,但对于新手(我们都是)来说,这是一个有用的提示。
sender
将是按钮。您可以将任何您希望的内容应用到 sender
。你不需要一个出口来做到这一点。
斯威夫特 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)
}
斯威夫特 3:
设置按钮标题:
//for normal state:
my_btn.setTitle("Button Title", for: .normal)
// For highlighted state:
my_btn.setTitle("Button Title2", for: .highlighted)
属性时更改标题有点不同:
我刚刚遇到了一个问题:如果你有一个带有属性标题的 UIButton,你必须使用:
my_btn.setAttributedTitle(NSAttributedString(string: my_title), for: my_state)
根据 Apple SetTitle Doc :
如果您同时为按钮设置标题和属性标题,则按钮更喜欢使用属性标题而不是这个标题。
我有一个属性标题,我试图在它上面设置标题,但没有效果......
斯威夫特 3
当您进行@IBAction 时:
@IBAction func btnAction(_ sender: UIButton) {
sender.setTitle("string goes here", for: .normal)
}
这会将发送方设置为 UIButton(而不是 Any),因此它将 btnAction 定位为 UIButton
迅捷4.2及以上
使用按钮的 IBOutlet
btnOutlet.setTitle("New Title", for: .normal)
使用按钮的 IBAction
@IBAction func btnAction(_ sender: UIButton) {
sender.setTitle("New Title", for: .normal)
}
//对于正常状态:
btnSecurite.setTitle("TextHear", for: .normal)
截至 2021 年 12 月 12 日 - Swift 版本 5.5.1^ 假设您已经有一个以正常状态链接到 yourButton 的 IBOutlet。
yourButton.setTitle("Title of your button", for: .normal)
斯威夫特 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)
要使用 swift - 04 在 Xcode 中为按钮设置标题:首先创建一个名为 setTitle 的方法,其参数为 title 和 UIController 状态,如下所示;
func setTitle(_ title : String?, for state : UIControl.State) {
}
并在您的按钮操作方法中调用此方法,例如;
yourButtonName.setTitle("String", for: .state)
UIControlState
。例如forState: .Normal
.normal
注意小写forState
更改为for
button.setTitle("Button Title",for: .normal)
工作!谢谢