如何通过单击另一个按钮来更改按钮的文本? - 斯威夫特

时间:2015-08-27 22:53:12

标签: swift uibutton

基本上这就是我尝试过的:

@IBAction func buttonTwo(sender: UIButton){  // <- Should UIButton be AnyObject ? 
 buttonOne.setTitle("Do", forState: .Normal) // This wont change the other buttons text 
}

//在知道如何做之后,我的目标是遵循这个逻辑:

@IBAction func buttonTwo(sender: UIButton) {
    if ( buttonOne == "What") {
         buttonOne.setTitle("Do", forState: .Normal)
    } else {
         buttonOne.setTitle(¨What", forState: .Normal)
        }  
}

1 个答案:

答案 0 :(得分:0)

我认为这就是你要找的东西:

@IBAction func buttonTwo(sender: UIButton) {
    if let text = buttonOne.titleForState(UIControlState.Normal) { //make sure title is not nil
        if ( text == "What") {
            buttonOne.setTitle("Do", forState: .Normal)
        } else {
            buttonOne.setTitle("What", forState: .Normal)
        }  
    }
}

我跑得很好:

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var buttonOne: UIButton!

    @IBAction func changeText(sender: AnyObject) {

        if let text = buttonOne.titleForState(UIControlState.Normal) {
            if ( text == "What") {
                buttonOne.setTitle("Do", forState: .Normal)
            } else {
                buttonOne.setTitle("What", forState: .Normal)
            }  
        }

    }


    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

你确定@IBOutlet是否正确连接到buttonOne?

注意:从故事板创建@IBAction时,它会将发件人设置为AnyObject。我改变了它,看它是否像UIButton那样有效。

像你问的数组选项

class ViewController: UIViewController {

@IBOutlet weak var buttonOne: UIButton!

var buttonArray:[UIButton] = []

@IBAction func changeText(sender: UIButton) {
    if let text = buttonArray[0].titleForState(UIControlState.Normal) {
        if ( text == "What") {
            buttonArray[0].setTitle("Do", forState: .Normal)
        } else {
            buttonArray[0].setTitle("What", forState: .Normal)
        }  
    }

}


override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    buttonArray.append(buttonOne)
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


}
相关问题