单击按钮时删除按钮上的选定状态(Swift)

时间:2016-02-01 07:56:47

标签: ios swift uibutton touch-up-inside

我试图找出在Swift中切换按钮状态的逻辑。这个概念非常简单:

  • 屏幕上有三个按钮。
  • 当我点击一个按钮时,它会切换到“选定”状态
  • 当我点击其他按钮时,我希望它将当前所选按钮切换为“未选中”状态并将新按钮切换为“已选择”

我在TouchUpInside上使用了这个功能,用于屏幕上的按钮,但目前可以将它们全部“选中”,这是我不想要的:

namespace AbcException;
use Exception;

class AbcException extends Exception {
    // Your Code
}

我来自Javascript的世界所以我可能只是将我的逻辑划掉了但是有没有办法检测屏幕上当前选择的按钮并关闭它们或者这更接近“无线电”按钮类型逻辑? / p>

我的问题是这些按钮是根据某些条件以编程方式创建的,所以从技术上讲,我不应该像正确的那样动态创建IBOutlets(IB意味着'Interface Builder'?)?

感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

SELECT
   Total_Rows= SUM(st.row_count)
FROM
   sys.dm_db_partition_stats st
WHERE
    object_name(object_id) = 'TABLENAME' AND (index_id < 2)

答案 1 :(得分:0)

使用TouchUpInside控制事件将所有三个按钮连接以下动作功能。

button1.addTarget(self, action: #selector(self.highlightTrack(button:)), for: .touchUpInside)
button2.addTarget(self, action: #selector(self.highlightTrack(button:)), for: .touchUpInside)
button3.addTarget(self, action: #selector(self.highlightTrack(button:)), for: .touchUpInside)

@IBAction func highlightTrack(button: UIButton) {

   if button.isSelected {
     return
   }

   button1.isSelected = false
   button1.backgroundColor = UIColor.white

   button2.isSelected = false
   button2.backgroundColor = UIColor.white

   button3.isSelected = false
   button3.backgroundColor = UIColor.white

   button.isSelected = true
   button.backgroundColor = UIColor.blue

}

另一种解决方案:

@IBAction func highlightTrack(button: UIButton) {

   if button.isSelected {
     return
   }

   updateButtionSelectionState(button: button, isSelected: (button == button1))
   updateButtionSelectionState(button: button, isSelected: (button == button2))
   updateButtionSelectionState(button: button, isSelected: (button == button3))

}


func updateButtionSelectionState(button: UIButton, isSelected: Bool) {
   button.isSelected = isSelected
   button.backgroundColor = isSelected ? UIColor.blue : UIColor.white
}