【问题标题】:How do I capture a button event type in swift如何快速捕获按钮事件类型
【发布时间】:2015-08-28 21:47:51
【问题描述】:

我无法找到有关如何捕获触摸事件的信息。 Event.type 和 event.description 对我没有帮助,据我所知,文档没有示例。

我正在几个按钮上创建一个 IBAction,并希望(共享)操作来处理命名按钮(sender.currentTitle)和(events.??)添加代码来确定按钮是被点击还是长按。

 @IBAction func ChangeSort(sender: UIButton, forEvent event: UIEvent!)     {
            //  Trying to capture the button action? Type?? Description?


 switch event.type   {
           case "Touch Up Inside":  
            //  Switching on currenttitle works fine.
            switch sender.currentTitle! {
            case "Amount":
                MyQueries.QppQueryOrderBy = "Order by Amount"
                //  Mylabel.text = "sss"
            default: ...
            }
        case "Touch Down Repeat":
            print("In long press")
            switch sender.currentTitle! {
            case "Amount":
                MyQueries.QppQueryOrderBy = "Order by Amount desc"
            default: ...
            }
        default:
            print("in def")
            switch sender.currentTitle! {
            case "Amount":...
                MyQueries.QppQueryOrderBy = "Order by LastActivityDate desc"
            default:
                MyQueries.QppQueryOrderBy = "Order by Amount desc"
            }

        }
        self.theTableView.reloadData()
}

【问题讨论】:

    标签: swift events ibaction


    【解决方案1】:

    您返回的UIEvent 不会告诉您您想要什么。 UIEvent 只会告诉你 Touches、Motion 或 Remote Control。您正在寻找 UIControlEvent,这在 iBAction 中很难找到。解决这个问题的更标准的方法是创建多个@IBAction func并将不同类型的控制事件分配给不同的事件。

    因此,对于所有命名按钮,您可以将 touch up inside 事件分配给相同的 sortByTitle func。

     @IBAction func sortByTitle(sender: UIButton)    {
            //  This is associated with TouchUpInside in IB
            switch sender.currentTitle! {
            case "Amount":
                MyQueries.QppQueryOrderBy = "Order by Amount"
                //  Mylabel.text = "sss"
            default: ...
            }
        self.theTableView.reloadData()
    
        }
    
        @IBAction func sortByTitleDescending(sender: UIButton)    {
            //This is associated with Touch Down Repeat
            print("In long press")
            switch sender.currentTitle! {
            case "Amount":
                MyQueries.QppQueryOrderBy = "Order by Amount desc"
            default: ...
            }
                  self.theTableView.reloadData()
          }
    

    基本上,如果您要在代码中创建按钮,当您初始化它时,您会使用 UIControl/UIButton 上的 addTarget 方法为要监视的每个控件事件添加一个 func。在addTarget 中,您为每个函数指定不同的函数。在 IB 中,您只是以图形形式执行此操作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-19
      • 2013-01-30
      相关资源
      最近更新 更多