Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load JSON array data into UIActionSheet button title using Swift

Tags:

ios

swift

I have JSON data within array. This array data I need to load into UIActionSheet button title. Here, I tried to create a common UIActionSheet with single button. Based on array strings I need to load data as a button title. I am sure, I never get above 4 array index from JSON, So I would like to load it into action sheet and based on click to get id value. I don’t know how to load it, as a button title.

My JSON Codable

   // MARK: - Welcome
struct Welcome: Codable {
    let status: Bool
    let data: DataClass
}

// MARK: - DataClass
struct DataClass: Codable {
    let id, rollnum, osname, dataDescription: String
    let team: [Team]
    let record, score: [String]
    let titles: [Title]

    enum CodingKeys: String, CodingKey {
        case id, rollnum, osname
        case dataDescription = "description"
        case team, record, score, titles
    }
}

// MARK: - Team
struct Team: Codable {
    let name, group: String
}

// MARK: - Title
struct Title: Codable {
    let status, id, icon: String
}

JSON Decoder

var titleData = [Title]()

override func viewDidLoad() {
    super.viewDidLoad()
    self.loadJSON()
}

// MARK: JSON Data Load

func loadJSON(){
    let urlPath = ""
    let url = NSURL(string: urlPath)
    let session = URLSession.shared
    let task = session.dataTask(with: url! as URL) { data, response, error in
        guard data != nil && error == nil else {
            print(error!.localizedDescription)
            return
        }
        do {
            let decoder = try JSONDecoder().decode(Welcome.self,  from: data!)
            self.titleData = decoder.data.titles
        } catch { print(error) }
    }
    task.resume()
}

Objective C Sample Need to change Swift 5

NSArray *array = @[@"1st Button",@"2nd Button",@"3rd Button",@"4th Button"];

    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"Title Here"
                                                             delegate:self
                                                    cancelButtonTitle:nil
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:nil];

    // ObjC Fast Enumeration
    for (NSString *title in array) {
        [actionSheet addButtonWithTitle:title];
    }

    actionSheet.cancelButtonIndex = [actionSheet addButtonWithTitle:@"Cancel"];

    [actionSheet showInView:self.view];

Exact Output

enter image description here

like image 395
myapp store Avatar asked Jan 02 '26 03:01

myapp store


1 Answers

Just loop and add action to ActionSheet

@IBAction func ClickAction(_ sender: Any) {

    let actionSheetAlertController: UIAlertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)

    for title in self.titleData {
      let action = UIAlertAction(title: title.status, style: .default) { (action) in
        print("Title: \(title.id)")
      }

      let icon = UIImage.init(named: title.icon)

      action.setValue(icon, forKey: "image")
      action.setValue(CATextLayerAlignmentMode.left, forKey: "titleTextAlignment")

      actionSheetAlertController.addAction(action)
    }

    let cancelActionButton = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
    actionSheetAlertController.addAction(cancelActionButton)

    self.present(actionSheetAlertController, animated: true, completion: nil)
  }
like image 107
Thanh Vu Avatar answered Jan 04 '26 13:01

Thanh Vu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!