问题描述:

My UIButton is in a UICollectionviewcell, which is in a UICollectionview, which is in a UITableViewCell, which is in a UITableView.

The button is a like button, I want it to change its text when clicked. But after changing the text, it returns the original value. What might be the reason here?

Here is what it looks like:

https://gfycat.com/UnlawfulGroundedErin

This is the onClickEvent of button:

@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"

}

}

网友答案:

try this

@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)
}
}

Choice-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
    }
}
网友答案:

Try This. It will work properly

@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 have different texts for its title in different states.

Just for your knowledge

In viewDidLoad:

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

then in method actionClick: if you write only one statement,

sender.selected = !sender.selected;

it will work.

相关阅读:
Top