【问题标题】:Xcode v7.2 - New Radio Buttons: How to find selectedXcode v7.2 - 新的单选按钮:如何找到选中的
【发布时间】:2015-12-12 19:35:54
【问题描述】:

我正在尝试使用 Xcode 7 的新单选按钮模板 (NSButton) 检测当前选择了哪个单选按钮。

我创建了一个简单的动作,将打印以在选择单选按钮时记录发件人的标题。这确实有效:

@IBAction func radioButtonClicked(sender: AnyObject)
    {
    print(sender.selectedCell()!.title);
    }

但我真正想要的是能够知道在我的代码中的其他地方选择了哪个单选按钮(特别是在按钮单击的 IBAction 上)。我试过了:

@IBAction func uploadButtonPressed(sender: AnyObject)
    {
    print (radioButton.selectedCell()!.title);
    }

这确实编译和执行,问题是它总是给我第一个单选按钮的标题而不是实际选择的那个。

有什么想法吗?


我能得到的“最接近”(不是很干净,但工作“有点”)是查看是否 radioButton.cell?state = 1。这告诉我选择了第一个单选按钮。但这是一种非常糟糕的编码方式,仅允许 2 个单选按钮选项。
if (radioButton.cell?.state == 1)
    {
    print ("Radio 1 Selected");
    }
else
    {
    print ("Radio 2 Selected");
    }

【问题讨论】:

    标签: swift macos interface-builder xcode7 nsbutton


    【解决方案1】:

    使用 Interface Builder 中的标识符或标签属性来区分单选按钮,例如:

    @IBAction func selectOption(sender: AnyObject) {
        let id:String = sender.identifier!!
        case "first identifier":
            // do some stuff
            // ...
        default:
            // do default stuff
    }
    

    另一个选项是 switch-case 语句并为每个单选按钮定义插座,例如:

    @IBOutlet weak var firstOption: NSButton!
    @IBOutlet weak var secondOption: NSButton!
    @IBOutlet weak var thirdOption: NSButton!
    
    @IBAction func selectOption(sender: AnyObject) {
    
        switch sender as! NSButton {
        case firstOption:
            print("firstOption")
        case secondOption:
            print("secondOption")
        case thirdOption:
            print("thirdOption")
        default:
            print("won't be called when exhaustive but must always be implemented")
        }
    }
    

    【讨论】:

      【解决方案2】:

      我最终找到了一种方法。

      首先我设置了一个变量来存储检查过的项目(并将值预先设置为我想要的第一个单选按钮的值)

      var databaseUploadMethod = "trickle-add";
      

      然后我比较看看选中项的title值:

      @IBAction func radioButtonClicked(sender: AnyObject)
          {
          if ((sender.selectedCell()!.title) == "Trickle Add")
              {
              databaseUploadMethod = "trickle-add";
              }
          else if ((sender.selectedCell()!.title) == "Bulk Add All Now")
              {
              databaseUploadMethod = "bulk-add";
              }
          }
      

      供参考:我有两个单选按钮,第一个的标题是“Trickle Add”,第二个是“Bulk Add All Now”。这些是我在 if 语句中比较的值。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-12-17
        • 1970-01-01
        • 1970-01-01
        • 2012-03-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多