[英]Swift - Why does my UIButton need to be double tapped to be in its selection state?
我有一個 UIButton,預期的行為是當它被點擊時,它應該具有藍色背景色,當未點擊時,它應該是白色。 但是,我總是必須在第一次嘗試時雙擊它才能被選中......這是為什么?
class CheckmarkCell: UITableViewCell {
static let reuseIdentifier = String(describing: CheckmarkCell.self)
@IBOutlet private weak var titleLabel: UILabel!
@IBOutlet private weak var yesButton: UIButton!
private weak var delegate: CheckmarkCellDelegate?
private var value: Bool?
public func configure(title: String, value: Bool?, delegate: CheckmarkCellDelegate? = nil) {
self.titleLabel.text = title
self.value = value
self.delegate = delegate
self.yesButton.layer.masksToBounds = true
self.yesButton.layer.cornerRadius = self.yesButton.frame.width / 2
self.yesButton.layer.borderWidth = 1.0
self.yesButton.layer.borderColor = UIColor.NBABlue?.cgColor
self.yesButton.backgroundColor = UIColor.white
// This is the dot
self.yesButton.tintColor = UIColor.clear
// This block of code saves the values. If it is removed, when you scroll, values will all be deselected and false.
switch self.value {
case true:
// This is the saved state
self.yesButton.backgroundColor = UIColor.NBABlue
self.yesButton.tintColor = UIColor.clear
// Deselected, should e white.
case false:
self.yesButton.backgroundColor = UIColor.white
self.yesButton.tintColor = UIColor.clear
default:
break
}
}
@IBAction func buttonTapped(_ sender: UIButton) {
if sender.isSelected {
yesButton.isSelected = false
// The selected state
self.yesButton.backgroundColor = UIColor.NBABlue
self.yesButton.tintColor = UIColor.clear
if self.value == nil || self.value == false {
self.value = true
self.delegate?.checkmarkCell(self, selectedValue: self.value!)
}
} else {
yesButton.isSelected = true
self.yesButton.backgroundColor = UIColor.white
self.yesButton.tintColor = UIColor.clear
if self.value == nil || self.value == true {
self.value = false
self.delegate?.checkmarkCell(self, selectedValue: self.value!)
}
}
}
}
單元格被重用在configure
添加這個
self.yesButton.tintColor = UIColor.clear // below this
self.yesButton.isSelected = self.value
要刪除藍色背景,您必須從故事板中清除色調。
在節文件 IBAction 中寫下這一行。
sender.isSelected = !sender.isSelected
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.