简体   繁体   English

具有唯一标识符的 UIButton

[英]UIButton With Unique Identifier

Searched questions here This but not completely solving my problem.在这里搜索问题但没有完全解决我的问题。

Problem here is I have around 100 buttons in UIScrollView, and based on response from server I have to highlight buttons (ie Server sends me "Button_Unique_Id": "Button_ABC_1").这里的问题是我在 UIScrollView 中有大约 100 个按钮,根据服务器的响应,我必须突出显示按钮(即服务器发送给我“Button_Unique_Id”:“Button_ABC_1”)。 Now here the problem is how do I create a UIButton with unique identifier "Button_ABC_1", in such a way that when I get response from server, I can identify my button with the Button_Unique_Id value and do alterations just to that button.现在的问题是我如何创建一个具有唯一标识符“Button_ABC_1”的 UIButton,这样当我从服务器得到响应时,我可以用 Button_Unique_Id 值识别我的按钮并只对该按钮进行更改。

button.tag = index

This approach fails as I can't identify button with value I got "Button_ABC_1"这种方法失败了,因为我无法识别具有“Button_ABC_1”值的按钮

I would appreciate response best practiced.我将不胜感激响应最佳实践。

Dictionary ( [String : UIButton] ) 中保留对按钮的引用,并将这些字符串用作键,然后您可以通过简单地请求来获得适当的按钮:

let buttonOfInterest = buttons["Button_ABC_1"]

Just create subclass of UIButton and add id instance variable whatever type you want.只需创建UIButton子类并添加您想要的任何类型的id实例变量。 Good Luck!祝你好运!

EDIT编辑

class MyButton: UIButton {
    var id : String?
}

Usage:用法:

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

Something like that.类似的东西。

You can use Button.tag = integerValue for storing integer value with button.您可以使用Button.tag = integerValue来存储带有按钮的整数值。 You can manage an array of those data and bind that array with button tag.您可以管理这些数据的数组并将该数组与按钮标签绑定。

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 }

Using forEach loop you can tag (integer value) the buttons at once使用 forEach 循环,您可以一次标记(整数值)按钮

updateButton(with tag: buttonIdentifier.id)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM