【问题标题】:UIAlertController 'UIAlertAction' tag/userdata or anything in SwiftUIAlertController 'UIAlertAction' 标签/用户数据或 Swift 中的任何内容
【发布时间】:2015-05-17 11:26:55
【问题描述】:

在我的 iOS 操作表中,我显示了 JSON 字典中的名称:

[
  { "Name": "Doctor for Disease AAA",
    "Doctor_id": "21"
  },
  { "Name": "Doctor for Disease BBB",
    "Doctor_id": "22"
  },
  { "Name": "Doctor for Disease AAA",
    "Doctor_id": "25"
  }
]

因此,在按钮单击委托上,我可以获得按钮索引,并可以获取相应的“名称”和“医生 ID”。这工作正常。

但现在似乎“UIActionSheet”已被弃用,我必须使用“UIAlertController”。由于我有大量数据,我正在遍历我的数组值并调用 alertcontroller 处理程序(因此所有按钮单击的单个函数)。但是如何从 UIAlertController 获取按钮索引,以便我可以同时获取“名称”和“医生 ID”。

请帮帮我。

【问题讨论】:

    标签: ios swift uialertcontroller


    【解决方案1】:

    这里有多种可能性。

    您可以使用find 获取UIAlertAction 索引

    find 让您在数组中找到对象的索引。你可以用它来findaction的索引(即作为UIAlertAction的处理程序的参数传递,即UIAlertAction本身)在所有操作的alert.actions数组中。

    let alert = UIAlertController(title: "Doctors", message: "Choose a doctor", preferredStyle: .ActionSheet)
    let closure = { (action: UIAlertAction!) -> Void in
        let index = find(alert.actions as! [UIAlertAction], action)
        println("Index: \(index)")
    }
    alert.addAction(UIAlertAction(title: "Doc1", style: .Default, handler: closure))
    alert.addAction(UIAlertAction(title: "Doc2", style: .Default, handler: closure))
    alert.addAction(UIAlertAction(title: "Doc3", style: .Default, handler: closure))
    alert.addAction(UIAlertAction(title: "Doc4", style: .Default, handler: closure))
    alert.addAction(UIAlertAction(title: "Cancel", style: .Cancel) { _ in
        println("User cancelled.")
    })
    self.presentViewController(alert, animated: true) {}
    

    你可以创建一个闭包……返回一个闭包

    创建一个带有您选择的参数的闭包(此处为Int)并返回一个捕获该参数的闭包,以便您可以使用它

     let alert = UIAlertController(title: "Doctors", message: "Choose a doctor", preferredStyle: .ActionSheet)
     let closure = { (index: Int) in
         { (action: UIAlertAction!) -> Void in
             println("Index: \(index)")
         }
     }
     alert.addAction(UIAlertAction(title: "Doc1", style: .Default, handler: closure(0)))
     alert.addAction(UIAlertAction(title: "Doc2", style: .Default, handler: closure(1)))
     alert.addAction(UIAlertAction(title: "Doc3", style: .Default, handler: closure(2)))
     alert.addAction(UIAlertAction(title: "Doc4", style: .Default, handler: closure(3)))
     alert.addAction(UIAlertAction(title: "Cancel", style: .Cancel) { _ in
         println("User cancelled.")
     })
     self.presentViewController(alert, animated: true) {}
    

    这样你就有了一个函数(闭包),它为你的UIAlertAction 处理程序生成闭包,除了它们捕获不同的对象(这里是不同的Int)之外,它们都具有相同的主体。

    此解决方案的真正优点在于您可以捕获任何内容。您甚至可以捕获代表您的医生的假设 Doctor 对象,或者直接捕获医生 ID 等!

    使用循环

    但通常你会使用for 循环添加你的动作,所以为什么不利用它,加上利用闭包和它们捕获变量的事实,来制作一个很好的函数,直接告诉你选择医生的身份证?

    func testMyAlert() {
        let doctors = [
            ["Name": "Doctor for Disease AAA", "Doctor_id": "21"],
            ["Name": "Doctor for Disease BBB", "Doctor_id": "22"],
            ["Name": "Doctor for Disease AAA", "Doctor_id": "25"]
        ]
    
        chooseDoctor(doctors) { selectedDocID in
            if let docID = selectedDocID {
                println("User selected doctor with ID \(docID)")
            } else {
                println("User cancelled, no doctor selected")
            }
        }
    }
    
    func chooseDoctor(doctors: Array<[String:String]>, completion: Int?->Void) {
        let alert = UIAlertController(title: "Doctors", message: "Choose a doctor", preferredStyle: .ActionSheet)
        for doc in doctors {
            let action = UIAlertAction(title: doc["Name"]!, style: UIAlertActionStyle.Default) { _ in
                // On selecting this action, get the doctor's ID, convert it to an Int, and return that.
                completion(doc["Doctor_id"]?.toInt())
            }
            alert.addAction(action)
        }
        alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) { _ in completion(nil) } )
        self.presentViewController(alert, animated: true) {}
    
    }
    

    【讨论】:

    • @AliSoftware 我可以在 Objective C 中获取闭包代码吗?
    【解决方案2】:

    您可以通过以下方式解决问题:

    let arraySelect = ["NewYork", "Washington", "Seoul", "Tokyo", "Peking", "Sidney", ... ]
    
    let alert = UIAlertController(title: nil, message: nil, preferredStyle: .Alert)
    
    let closure = { (action: UIAlertAction!) -> Void in 
        let index = alert.actions.indexOf(action)
        if index != nil {
            NSLog("Index: \(index!)") 
        }
    }
    
    for var i = 0; i < arrayBibleVersions.count; i++ { alert.addAction(UIAlertAction(title: arrayBibleVersions[i][1], style: .Default, handler: closure)) }
    
    alert.addAction(UIAlertAction(title: "cancel", style: .Cancel, handler: {(_) in }))
    
    self.presentViewController(alert, animated: false, completion: nil)
    

    【讨论】:

      【解决方案3】:

      您可以调用 indexOf(element: Self.Generator.Element) 从您的控制器收集您的操作。

      类似:

      let actionSheetController = UIAlertController(title: "Title", message: "Select Title", 
                                                    preferredStyle: UIAlertControllerStyle.ActionSheet);
      
      for entry in data {
         let myAction = UIAlertAction(title: "title: \(entry)", style: UIAlertActionStyle.Default) { (action) -> Void in
            if let alertIndex = actionSheetController.actions.indexOf(action) {
              print("actionIndex: \(alertIndex)")
            }
         }
         actionSheetController.addAction(myAction)
      }
      

      【讨论】:

        【解决方案4】:

        我发现使用自定义 UIAlertAction 类而不是使用索引更容易且更具表现力

        class MyAlertAction:UIAlertAction {
            var key:String = ""
            convenience init(key:String, title:String, handler:((UIAlertAction) -> ())?) {
                self.init(title: title, style: .default, handler: handler)
                self.key = key
            }
        }
        

        在您的操作处理程序中,您会得到这样的键:

        let actionHandler: (UIAlertAction) -> () = { (action) in
            if let key = (action as? MyAlertAction)?.key {
                 //use the key
            }
        }
        

        最后使用你的新类来添加一个动作

        alert.addAction(MyAlertAction(key:"doctor32", title: "Title", handler: actionHandler))
        

        【讨论】:

          【解决方案5】:

          我建议您在需要时将闭包传递给调用。它的按需。也许这样的事情会有所帮助。

          var alert = UIAlertController(title: "Title", message: "do this", preferredStyle: UIAlertControllerStyle.ActionSheet)
              var action = UIAlertAction(title: "Doc1", style: UIAlertActionStyle.Default) { (action) -> Void in
                  //do some work here
              }
          

          但是,我想您在操作表上显示的项目不超过 4 个,因为它不利于设计。关闭可能是个好主意。如果我弄错了建议我,我很乐意帮助你。干杯。

          【讨论】:

            【解决方案6】:

            您可以通过创建一个或多个 UIAlertAction 对象并将其附加到警报控制器来将按钮添加到 UIAlertController。每个警报操作都有一个标题(用于创建它的按钮)和一个在用户点击该按钮时被调用的闭包。

            您是说要对所有按钮使用相同的闭包吗?我看到了很多选项

            1. 您可以为每个警报操作编写唯一的闭包,其中闭包只是调用一个共享函数并传入一个按钮编号。

            2. 或者,UIAlertAction 的闭包在被点击的按钮的标题中传递。您可以使用它来决定点击哪个按钮。 (这很脆弱,因为按钮标题可能已本地化,并且可能会因 UI 原因而更改。UI 更改中断代码时会很糟糕。)

            3. 作为最后一个选项,您可以使用关联存储将对象附加到每个 UIAlertAction 并使用它来确定点击了哪个按钮。

            我的建议是选项 1。它简单明了。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2017-01-25
              • 2016-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2018-05-26
              • 1970-01-01
              相关资源
              最近更新 更多