【问题标题】:UIButton With Unique Identifier具有唯一标识符的 UIButton
【发布时间】:2018-03-01 13:16:03
【问题描述】:

在这里搜索的问题 This 但不能完全解决我的问题。

这里的问题是我在 UIScrollView 中有大约 100 个按钮,并且根据来自服务器的响应,我必须突出显示按钮(即服务器向我发送“Button_Unique_Id”:“Button_ABC_1”)。现在这里的问题是我如何创建一个具有唯一标识符“Button_ABC_1”的 UIButton,这样当我从服务器获得响应时,我可以用 Button_Unique_Id 值识别我的按钮并仅对该按钮进行更改。

button.tag = index

此方法失败,因为我无法识别具有“Button_ABC_1”值的按钮

我希望得到最佳实践的响应。

【问题讨论】:

  • 请出示您的代码好吗?

标签: ios swift3 uibutton


【解决方案1】:

Dictionary ([String : UIButton]) 中保留对您的按钮的引用并将这些字符串用作键,然后您只需请求即可获得相应的按钮:

let buttonOfInterest = buttons["Button_ABC_1"]

【讨论】:

    【解决方案2】:

    只需创建UIButton 的子类并添加id 实例变量,无论您想要什么类型。祝你好运!

    编辑

    class MyButton: UIButton {
        var id : String?
    }
    

    用法:

    let btn = MyButton(type: .custom)
    btn.id = "MY_BUTTON_ID"
    

    类似的东西。

    【讨论】:

    • 你能给个例子或一些链接吗?我必须为每个 UIButton 创建子类吗?
    • 您不必为每个按钮创建子类。创建后,只需将您的唯一 id 分配给按钮,并将引用保存在数组或字典中,以便以后识别按钮。
    • 好的,我正在尝试这个解决方案。过一会儿就会回来。
    • 我认为这个解决方案最终会添加到 Dictionary like ([String : UIButton])
    【解决方案3】:

    您可以使用Button.tag = integerValue 通过按钮存储整数值。 您可以管理这些数据的数组并将该数组与按钮标签绑定。

    【讨论】:

      【解决方案4】:
      enum ButtonIdentifier: String {
      //you could name the enum as ButtonMapper
      //let the case be same as server response string
      case button_abc_0
      case button_abc_1
      case button_abc_2
      
      var id: int {
      //fetch the id from the server response string & return - here fetch the integer from the rawValue.
      //Or else you have to use the switch for returning the id which is not feasible when you have 100s of data - better to extract from the response string
      }
      
      guard let buttonIdentifier = ButtonIdentifier (rawValue: serverResponceString) else { return }
      

      使用 forEach 循环,您可以一次标记(整数值)按钮

      updateButton(with tag: buttonIdentifier.id)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-03
        • 2013-05-07
        • 2022-07-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多