1

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 (i.e. Server sends me "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.tag = index

This approach fails as I can't identify button with value I got "Button_ABC_1"

I would appreciate response best practiced.

niravdesai21
  • 4,818
  • 3
  • 22
  • 33

4 Answers4

2

Keep references to your buttons in a Dictionary ([String : UIButton]) and use those strings as keys, then you can get the appropriate button by simply asking for it:

let buttonOfInterest = buttons["Button_ABC_1"]
Milan Nosáľ
  • 19,169
  • 4
  • 55
  • 90
1

Just create subclass of UIButton and add id instance variable whatever type you want. Good Luck!

EDIT

class MyButton: UIButton {
    var id : String?
}

Usage:

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

Something like that.

Fahri Azimov
  • 11,470
  • 2
  • 21
  • 29
1

You can use Button.tag = integerValue for storing integer value with button. You can manage an array of those data and bind that array with button tag.

Wilson Vargas
  • 2,841
  • 1
  • 19
  • 28
Sharad Paghadal
  • 2,089
  • 15
  • 29
0
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

updateButton(with tag: buttonIdentifier.id)
Nagaraj
  • 23
  • 1
  • 5