如何使用Swift中的函数更改标签后的原始文本?

时间:2015-09-05 16:45:05

标签: ios xcode swift

我有一个按钮可以在按下时更改文本视图,我想让它在再次按下按钮时将更改后的文本切换为原始文本。

我的代码:

    //An IBOutlet for the textview
    @IBOutlet weak var changingText: UITextView!

    //The button that changed the text
    @IBAction func viewChangedText(sender: AnyObject) {

    changingText.text = "Changed Text"

}

现在我希望在再次按下按钮时更改文本。

注意:原始文本位于故事板中,如果可能的话。你可以帮我在原始文本出现时将按钮的文本更改为“查看”,并在更改的文本出现时将按钮的文本更改为“隐藏”。

2 个答案:

答案 0 :(得分:0)

        var didChange = false
        @IBOutlet weak var changingText: UITextView!

        //The button that changed the text
        @IBAction func viewChangedText(sender: AnyObject) {
        didChange = !didChange
        if didChange {
          changingText.text = "Changed Text"
        }else{
          changingText.text = "Original text"
        }
    }

答案 1 :(得分:0)

@nathanwhy对switch-bool有个好主意。基于这个想法,你可以有这样的东西:

@IBOutlet weak var changingTextView: UITextView!

var showOriginalText : Bool {
    didSet {
        changingTextView.text = showOriginalText ? "original text" : "other text"
    }
} 

override func viewDidLoad() {
    super.viewDidLoad()
    // or wherever else it makes sense
    showOriginalText = true
}


@IBAction func changeButtonTapped(sender: UIButton) {
    showOriginalText = !showOriginalText
}