![](/img/trans.png)
[英]How can I fill a TableViewCell with an array that comes from web service?
[英]How to conform an array from another array that comes from a REST Service?
我正在嘗試使用來自REST服務的元素創建TableView,這是一張包含說明,標題,類別和圖像的優惠券列表。 因此,我首先對數據進行反序列化,然后將其放入一個數組中,然后在每個部分將其轉換為特定的數組,但是我的循環不起作用,有人可以幫我嗎?
這是我的代碼:
var couponsTitle : [String] = []
var couponsDesc : [String] = []
var couponsCat : [String] = []
func getCoupons(){
let miURL = URL(string: RequestConstants.requestUrlBase)
let request = NSMutableURLRequest(url: miURL!)
request.httpMethod = "GET"
if let data = try? Data(contentsOf: miURL! as URL) {
do {
let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? NSDictionary
let parseJSON = json
let object = parseJSON?["object"] as! NSDictionary
let mainCoupon = object["mainCoupon"] as! NSArray
let coupons = object["coupons"] as! NSArray
for i in mainCoupon {
self.couponsCat.append((mainCoupon[i as! Int] as AnyObject).value(forKey: "category"))
}
for i in coupons {
self.couponsCat.append((coupons[i as! Int] as AnyObject).value(forKey: "category"))
}
for i in mainCoupon {
self.couponsDesc.append((mainCoupon[i as! Int] as AnyObject).value(forKey: “description"))
}
for i in coupons {
self.couponsDesc.append((coupons[i as! Int] as AnyObject).value(forKey: “description"))
}
for i in mainCoupon {
self.couponsTitle.append((mainCoupon[i as! Int] as AnyObject).value(forKey: “name"))
}
for i in coupons {
self.couponsTitle.append((coupons[i as! Int] as AnyObject).value(forKey: “name"))
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! HomeTableViewCell
cell.couponTitle.text = couponsTitle[indexPath.row]
cell.couponDescription.text = couponsDesc[indexPath.row].
cell.couponCategory.text = couponsCat[indexPath.row]
return cell
}
我最大的問題是,我不知道如何將數組放入循環中,而要知道每個部分的規范(我的意思是標題,描述,類別等)。
而不是擁有三個數組(每個屬性一個),為什么不為Coupon提供一個具有三個屬性的自定義類?
class Coupon: AnyObject {
var description: String
var title: String
var category: String
init(description: String, title: String, category: String) {
self.description = description
self.title = title
self.category = category
}
}
如果這樣做,可以通過執行以下操作避免很多循環
for coupon in mainCoupon {
let description = mainCoupon["description"]
let title = mainCoupon["name"]
let category = mainCoupon["category"]
let newCoupon = Coupon(description: description, title: title, category: category)
couponsArray.append(newCoupon)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.