I have JSON
内的数据array
。我需要加载这个数组数据UIActionSheet
button title
。在这里,我尝试使用单个创建一个通用的 UIActionSheetbutton
。基于数组字符串,我需要加载数据作为按钮标题。我确信,我从来没有从 JSON 中获得超过 4 个数组索引,所以我想将其加载到操作表中并根据单击获取 id 值。我不知道如何加载它,作为按钮标题。
我的 JSON 编码
// 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];
精确输出