gpt4 book ai didi

ios - 如何使用 Swift 将 JSON 数组数据加载到 UIActionSheet 按钮标题中

转载 作者:可可西里 更新时间:2023-11-01 01:06:56 25 4
gpt4 key购买 nike

我在 array 中有 JSON 数据。我需要将此数组数据加载到 UIActionSheet 按钮 title 中。在这里,我尝试创建一个带有单个 button 的通用 UIActionSheet。基于数组字符串,我需要将数据加载为按钮标题。我敢肯定,我从来没有从 JSON 中获得超过 4 个数组索引,所以我想将它加载到操作表中并基于点击获取 id 值。我不知道如何加载它,作为按钮标题。

我的 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 解码器

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 示例需要更改 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];

精确输出

enter image description here

最佳答案

只需循环并向 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)
}

关于ios - 如何使用 Swift 将 JSON 数组数据加载到 UIActionSheet 按钮标题中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57731866/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com