在開發中,常需要根據狀態改變按鈕文字,例如播放與暫停、開始與停止、收藏與取消收藏。UIButton 可以透過 setTitle 方法更新標題。
切換標題前,需要先知道按鈕目前顯示的文字。可以使用 currentTitle,也可以使用 titleForState。
if myBtn.currentTitle == "播放" {
myBtn.setTitle("暫停", for: .normal)
} else {
myBtn.setTitle("播放", for: .normal)
}
若想明確指定狀態,也可以這樣寫:
if myBtn.title(for: .normal) == "播放" {
myBtn.setTitle("暫停", for: .normal)
} else {
myBtn.setTitle("播放", for: .normal)
}
如果按鈕有多種狀態,例如 highlighted、selected、disabled,要確認 setTitle 的 for 參數是否正確,否則可能會在某些狀態下顯示錯誤文字。