2014-10-29 109 views
78

这就是我想要做的。如果你曾经玩过Halo或CoD,你会知道你可以改变武器装载的名字。如何更改Swift Xcode 6中的按钮文本?

我正在做的是让它可以使用文本字段来更改装载名称。这里的问题,在载出菜单载出的名字是一个按钮(选择和查看有关的载出的信息),我可以只写:

@IBAction func renameClassButton(sender: AnyObject) { 
    classTopButton.text = "\(classTopTextField)" 
} 

它除了[classTopButton]是一个按钮,不允许 '的.text' 后缀

回答

205

你可以这样做:

button.setTitle("my text here", forState: .Normal) 

斯威夫特3:

button.setTitle("my text here", for: .normal) 
+14

还是有点短。你可以省略'UIControlState'部分,只需像'button.setTitle(“我的文本在这里”,forState:.Normal)''写。 – mustafa 2014-10-29 22:52:04

+2

我认为这有助于提及:如果您利用Storyboard,'button'是一个'IBOutlet'(与包含这行代码的'IBAction'相反)。 – whalesharkie 2015-06-18 14:53:20

15

在Xcode中8 - 斯威夫特3

button.setTitle("entertext" , for: .normal)

+1

第二个参数现在是'.normal'而不是'.Normal'。 – 2017-07-20 20:48:59

+0

资本'.Normal'现在会出错。 Undercase现在是正确的。 '.normal' – 2017-09-17 05:53:29

0

您可以使用发件人的说法

@IBAction func TickToeButtonClick(sender: AnyObject) { 

     sender.setTitle("my text here", forState: .Normal) 


} 
0

请注意,如果你使用NSButton没有setTitle FUNC,相反,它是一个属性。

@IBOutlet weak var classToButton: NSButton! 

. . . 


classToButton.title = "Some Text" 
5

现在这是迅速3,

let button = (sender as AnyObject) 
    button.setTitle("Your text", for: .normal) 

(变量的常量声明是没有必要的只是确保你使用的发送者是这样的按钮):

(sender as AnyObject).setTitle("Your text", for: .normal) 

记住这是在你的按钮的IBAction中使用。

0

SWIFT 4工作,以及3

libero.setTitle("---", for: .normal) 

,其中自由人是一个UIButton

0

在斯威夫特4我想这一切之前,但只运行:

@IBAction func myButton(sender: AnyObject) { 
    sender.setTitle("This is example text one", for:[]) 
    sender.setTitle("This is example text two", for: .normal) 
} 
相关问题