![](/img/trans.png)
[英]How do I change a button's color when pressed and reset to original color when a different button is pressed?
[英]How to Change previous button color when pressed the next button?
我在水平UIScrollView
編程方式添加了許多按鈕。 我必須更改用戶選擇的按鈕的顏色。 但是,如果用戶選擇另一個按鈕,則先前的按鈕顏色必須更改為默認顏色。 我怎樣才能做到這一點? 請幫我...
func createHorizontalScroll()
{
let scrollView = UIScrollView(frame: CGRect(x: CGFloat(0), y: CGFloat(410), width: CGFloat(view.frame.size.width), height: CGFloat(40)))
var buttonX: CGFloat = 0
for index in 0..<btnNames.count
{
//add an element and the previous element together
let sum = btnNames[index]
button = UIButton(frame: CGRect(x: CGFloat(buttonX), y: CGFloat(0), width: CGFloat(100), height: CGFloat(40)))
print("btnNames:\(sum)")
button.setTitle("\(sum)",for:.normal)
button.layer.borderWidth = 2.5
button.layer.borderWidth = 2.5
button.layer.borderColor = UIColor.white.cgColor
button.layer.backgroundColor = UIColor.black.cgColor
button.tag = index
scrollView.addSubview(button)
buttonX = button.frame.size.width + buttonX
button.addTarget(self, action: #selector(changeView), for: .touchUpInside)
}
scrollView.contentSize = CGSize(width: CGFloat(buttonX), height: CGFloat(scrollView.frame.size.height))
scrollView.backgroundColor = UIColor.clear
view.addSubview(scrollView)
}
func changeView(_ sender: UIButton)
{
print("I Clicked a button \(Int(sender.tag))")
}
由於您已經在使用標簽,所以這不成問題。 changeView
函數應該像這樣工作:
func changeView(_ sender: UIButton)
{
let scrollView = sender.superview as! UIScrollView //This is mildly hacky - store your scroll view in an instance variable
for view in scrollView.subviews {
guard let button = view as? UIButton else {
continue
}
button.backgroundColor = sender.tag == button.tag ? UIColor.red : UIColor.black
}
}
沒有標簽的簡單解決方案。
聲明屬性currentButton
weak var currentButton : UIButton?
在changeView
重置的顏色currentButton
,設置的顏色sender
和分配sender
給currentButton
。
func changeView(_ sender: UIButton)
{
currentButton?.backgroundColor = .black
currentButton = sender
sender.backgroundColor = .red
}
由於可選鏈接的顏色currentButton
不會如果設置currentButton
是nil.
保留UIButton類型的week屬性以臨時保存所選按鈕。
weak var selectedButton: UIButton?
在按鈕的選擇器中,將selectedButton
的顏色設置為默認顏色,然后更改新選擇的按鈕的顏色並重置selectedButton
@IBAction func actionTouchUpInside(sender: UIButton) {
if let selectedButton = self.selectedButton {
selectedButton.backgroundColor = UIColor.clear
}
sender.backgroundColor = UIColor.blue
selectedButton = sender
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.