【发布时间】:2014-12-07 05:01:57
【问题描述】:
这里有一个简单的问题。我有一个 UIButton、currencySelector,我想以编程方式更改文本。这是我所拥有的:
currencySelector.text = "foobar"
Xcode 给我错误“预期声明”。我做错了什么,如何更改按钮的文本?
【问题讨论】:
这里有一个简单的问题。我有一个 UIButton、currencySelector,我想以编程方式更改文本。这是我所拥有的:
currencySelector.text = "foobar"
Xcode 给我错误“预期声明”。我做错了什么,如何更改按钮的文本?
【问题讨论】:
在 Swift 3、4、5 中:
button.setTitle("Button Title", for: .normal)
否则:
button.setTitle("Button Title", forState: UIControlState.Normal)
还必须为button 声明一个@IBOutlet。
【讨论】:
UIControlState。例如forState: .Normal
.normal 注意小写
forState 更改为 for
button.setTitle("Button Title",for: .normal) 工作!谢谢
只是对 Swift 和 iOS 编程新手的说明。下面的代码行:
button.setTitle("myTitle", forState: UIControlState.Normal)
仅适用于IBOutlets,不适用于IBActions。
因此,如果您的应用程序使用按钮作为函数来执行某些代码,例如播放音乐,并且您希望基于切换变量将标题从 Play 更改为 Pause,您还需要创建该按钮的IBOutlet。
如果您尝试对IBAction 使用button.setTitle,您将收到错误消息。一旦你知道它就很明显,但对于新手(我们都是)这是一个有用的提示。
【讨论】:
sender 将是按钮。您可以将任何您希望的内容应用到sender。你不需要一个出口来做到这一点。
斯威夫特 5.0
// Standard State
myButton.setTitle("Title", for: .normal)
【讨论】:
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)
如果您同时为按钮设置了标题和属性标题,则按钮更喜欢使用属性标题而不是这个。
我有一个属性标题,我尝试在其上设置标题,但没有任何效果...
【讨论】:
斯威夫特 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)
}
【讨论】:
//正常状态:
btnSecurite.setTitle("TextHear", 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)
【讨论】:
在 Xcode 中使用 swift - 04 为按钮设置标题: 首先创建一个名为 setTitle 的方法,其参数为 title 和 UIController 状态,如下所示;
func setTitle(_ title : String?, for state : UIControl.State) {
}
并在您的按钮操作方法中调用此方法 喜欢;
yourButtonName.setTitle("String", for: .state)
【讨论】:
截至 2021 年 12 月 12 日 - Swift 版本 5.5.1^ 假设您已经有一个正常状态下链接到 yourButton 的 IBOutlet。
yourButton.setTitle("Title of your button", for: .normal)
【讨论】: