class BigLabelButton: UIButton {
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
let bigLabel = UILabel()
var colorArray:[UIColor]?
var colorpressArray:[UIColor]?
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
bigLabel.text = "Long Press"
bigLabel.textColor = UIColor.white
bigLabel.shadowColor = UIColor.black
addSubview(bigLabel)
colorArray = [UIColor(red: 0.91, green: 0.26, blue: 0.12, alpha: 1),
UIColor(red: 0.98, green: 0.66, blue: 0.03, alpha: 1),
UIColor(red: 0.01, green: 0.63, blue: 0.51, alpha: 1),
UIColor(red: 0.04, green: 0.67, blue: 0.86, alpha: 1),
UIColor(red: 0.01, green: 0.5, blue: 0.81, alpha: 1)]
colorpressArray = [UIColor(red: 0.79, green: 0.15, blue: 0.00,alpha: 1),
UIColor(red: 0.86, green: 0.54, blue: 0.00,alpha: 1),
UIColor(red: 0.00, green: 0.51, blue: 0.40,alpha: 1),
UIColor(red: 0.00, green: 0.55, blue: 0.74,alpha: 1),
UIColor(red: 0.00, green: 0.38, blue: 0.70,alpha: 1)]
if colorArray != nil{
backgroundColor = colorArray![tag]
}
}
override var isHighlighted: Bool{
didSet{
guard colorArray != nil && colorpressArray != nil else { return}
switch isHighlighted{
case true:
backgroundColor = colorpressArray![tag]
bigLabel.textColor = UIColor.gray
case false:
backgroundColor = colorArray![tag]
bigLabel.textColor = UIColor.white
}
}
}
}
程式碼如下面, 最主要的是利用 didSet 的功能....
利用UIButton 的 內建變數 isHighlighted能夠知道 目前button的狀態
這一行就要把 optional 變數變成不是 optional
guard colorArray != nil && colorpressArray != nil else { return}
然後判斷 isHighlighted
當 isHighlighted 為 true
改變button 的background , 並且改變裡面label的textcolor
backgroundColor = colorpressArray![tag]
bigLabel.textColor = UIColor.gray
當 isHighlighted 為 false
backgroundColor = colorArray![tag]
bigLabel.textColor = UIColor.white
沒有留言:
張貼留言