UIButton文本在为其设置新值后返回原始值

时间:2016-01-13 08:39:07

标签: ios swift

我的UIButton位于UICollectionviewcell,位于UICollectionview,位于UITableViewCell,位于UITableView

按钮是一个类似的按钮,我希望它在单击时更改其文本。但是在更改文本后,它会返回原始值。这可能是什么原因?

以下是它的样子: https://gfycat.com/UnlawfulGroundedErin

这是按钮的onClickEvent

@IBAction func actionClick(sender: MyActionButton) {

    if (sender.toggle){
        print("Do dislike call here.")
        sender.toggle = false
        sender.titleLabel?.text = "Like"

    }else{
        print("Do like call here.")
        sender.toggle = true
        sender.titleLabel?.text = "Unlike"
    }

}

2 个答案:

答案 0 :(得分:2)

试一试。它将正常工作

@IBAction func actionClick(sender:MyActionButton){

    if (sender.toggle){
        print("Do dislike call here.")
        sender.toggle = false
        sender.titleLabel?.text = "Like"
        sender.setTitle("Like", forState: UIControlState.Normal)
    }else{
        print("Do like call here.")
        sender.toggle = true
        sender.setTitle("Unlike", forState: UIControlState.Normal)
    }

}

UIButton在不同的州有不同的标题文本。

仅供您参考

viewDidLoad:

 btnObject.setTitle("Like", forState: UIControlState.Normal)
 btnObject.setTitle("Unlike", forState: UIControlState.Selected)

然后在方法actionClick:中,如果只写一个语句,

sender.selected = !sender.selected;

它会起作用。

答案 1 :(得分:1)

试试这个

@IBAction func actionClick(sender: UIButton) {
if sender.isSelected() {
    sender.selected = false
    sender.setTitle("Like", forState: UIControlState.Normal)
}
else {
    sender.selected = true
    sender.setTitle("Unlike", forState: UIControlState.Normal)
}
}

<强>选择-2

var isSelectFirst:Bool = false

 @IBAction func actionClick(sender: UIButton) {

       if isHighLighted == false{
        sender.setTitle("Unlike", forState: UIControlState.Normal)
        isHighLighted = true
    }else{
         sender.setTitle("Like", forState: UIControlState.Normal)
        isHighLighted = false
    }
}