UIButton 文本不会保持变化

UIButton text not staying changing

我正在 Swift

中开发一个简单的 iPhone 应用程序

我有一个习惯UITableViewCell。在单元格中,我有一个普通的 UIButton,文本为 "Hello World"。

在我的自定义单元格代码中,我有以下功能:

@IBAction func buttonAction(sender: AnyObject) {

    if likeButton.titleLabel?.text == "Hello World" {

        likeButton.titleLabel?.text = "Hi!"

    }

}

当我点击 UIButton 时,UIButton 的文本瞬间变为 "Hi!"!然后它很快变回 "Hello World"...有什么办法可以解决这个问题吗?

为什么要这样做?

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

使用此代码

使用 UIButtons's setTitle: forState: 而不是在按钮的 titleLabel 上设置文本。例如-

初始设置

likeButton.setTitle("Hello World", forState: UIControlState.Normal)

点击设置-

@IBAction func buttonAction(sender: AnyObject) {

    if likeButton.titleLabel?.text == "Hello World" {
        likeButton.setTitle("Hi!", forState: UIControlState.Normal)
    }

}

做这样的事情:

@IBAction func buttonAction(发件人:AnyObject){

    likeButton.setTitle("Hi!", forState: UIControlState.Normal)

}

它在这里工作,希望也在那里工作,设置你的默认值-

yourButton.setTitle("Hello", forState: UIControlState.Normal)

当您点击按钮时设置此

@IBAction func buttonAction(sender: AnyObject) {

if yourButton.titleLabel?.text == "Hello " {
    yourButton.setTitle("Max", forState: UIControlState.Normal)
}

}