2016-01-13 11 views
-1

UIButton後處於UICollectionviewcell,這在UICollectionview,這在UITableViewCell,這是一個UITableViewUIButton的文本返回到原始值的新值設置爲它

該按鈕是一個像按鈕,我希望它點擊時改變其文本。但更改文字後,它會返回原始值。這可能是什麼原因?

這裏是什麼樣子: 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" 
    } 

} 

回答

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 
    } 
} 
+0

實際上,謝謝你! –

+0

歡迎兄弟... –

2

試試這個。它會正常工作

@IBAction FUNC actionClick(發件人: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; 

它會奏效。

+0

+爲答覆,這基本上是什麼「國家」。爲狀態配置標題一次,然後切換狀態 – Injectios

+0

@injections謝謝,對,這是使用狀態的正確方法 –