简体   繁体   中英

How to change button text in Swift Xcode 6?

Here's what I'm trying to do. If you've ever played Halo or CoD, you'd know that you could change the name of a weapon load-out.

What I'm doing is making it so you can change your load-out name using a text field. Here's the problem, the load-out name in the load-out menu is a button (to select and view info about that load-out) and I could just write this:

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

Except it [classTopButton] is a button which doesn't allow the '.text' suffix

You can do:

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

Swift 3 and 4:

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

在 Xcode 8 - Swift 3 中

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

It is now this For swift 3,

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

(The constant declaration of the variable is not necessary just make sure you use the sender from the button like this) :

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

Remember this is used inside the IBAction of your button.

NOTE:

line

someButton.setTitle("New Title", forState: .normal)

works only when Title type is Plain .

在此处输入图片说明

You can Use sender argument

  @IBAction func TickToeButtonClick(sender: AnyObject) {

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


}

swift 4 work as well as 3

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

where libero is a uibutton

Note that if you're using NSButton there is no setTitle func, instead, it's a property.

@IBOutlet weak var classToButton: NSButton!

. . .


classToButton.title = "Some Text"

In Swift 4 I tried all of this previously, but runs only:

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

Swift 5

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM