我基於x個獲取的數據動態創建x個按鈕數。一次只激活一個按鈕
而且我想一次只激活一個按鈕。 假設有3個按鈕,分別命名爲A,B,C。 當用戶點擊乙而一個是積極的,我想停用一個,使乙活躍。
這是容易實現的jQuery中這樣
$(this).toggleClass('checked').siblings().removeClass('checked');
我怎樣才能在斯威夫特做到這一點?
我創建的按鈕具有以下:
let frame1 = CGRect(x: 10, y: 6, width: 50, height: 30)
let button1 = UIButton(frame: frame1)
let attributedTitle = NSAttributedString(string: "\(distinctCategories[i])".uppercaseString, attributes: [NSKernAttributeName: 1.0, NSForegroundColorAttributeName: UIColor.blackColor()])
button1.setAttributedTitle(attributedTitle, forState: .Normal)
button1.titleLabel!.font = UIFont(name: "HelveticaNeue", size: 13.0)
button1.layer.borderWidth = 2.0
button1.layer.borderColor = UIColor.blackColor().CGColor
button1.backgroundColor = UIColor.whiteColor()
button1.addTarget(self, action: "filterByCategory:", forControlEvents: UIControlEvents.TouchUpInside)
self.categoryScrollView.addSubview(button1)
和目標的行動,我有:
func filterByCategory(sender:UIButton) {
if sender.backgroundColor != UIColor.blackColor() {
let attributedTitle = NSAttributedString(string: "\((sender.titleLabel?.text)!)".uppercaseString, attributes: [NSKernAttributeName: 1.0, NSForegroundColorAttributeName: UIColor.whiteColor()])
sender.setAttributedTitle(attributedTitle, forState: .Selected)
sender.backgroundColor = UIColor.blackColor()
} else {
let attributedTitle = NSAttributedString(string: "\((sender.titleLabel?.text)!)".uppercaseString, attributes: [NSKernAttributeName: 1.0, NSForegroundColorAttributeName: UIColor.blackColor()])
sender.setAttributedTitle(attributedTitle, forState: .Normal)
sender.backgroundColor = UIColor.whiteColor()
}
}
我只顯示在這裏爲簡潔風格的變化。 目前我只處理髮件人按鈕樣式的切換,而不是切換同級按鈕。
要反轉兄弟按鈕的樣式,我試過在上面的if
里加入這個。
for button in categoryScrollView.subviews {
if let button = button as? UIButton {
let attributedTitle = NSAttributedString(string: " ", attributes: [NSKernAttributeName: 1.0, NSForegroundColorAttributeName: UIColor.blackColor()])
button.setAttributedTitle(attributedTitle, forState: .Normal)
button.backgroundColor = UIColor.whiteColor()
}
}
但我不知道如果我這樣做的權利,因爲我需要在這個目標函數再次添加所有按鈕標題爲setAttributedTitle()
如何其他人在做的雨燕這個按鈕切換效果?
第一:存儲所創建的按鈕的陣列。然後:在'filterByCategory'裏面遍歷數組,「停用」每個不是「sender」的按鈕,並「激活」sender。 – luk2302