我之前从未使用过水平滚动表视图,因此我不知道如何使用REST API填充垂直可滚动表视图。我在这里找到了一个例子:
' https://github.com/ThornTechPublic/HorizontalScrollingCollectionView'
使用硬编码数据,但是当我使用来自WS的数据时,表格单元格没有显示任何内容。
这是我的代码(是最重要的类,因为它是符合TableCell的类,在这种情况下是一个进入CollectionView的单元格,这是我调用REST API的地方): / p>
class CategoryRow : UITableViewCell {
@IBOutlet weak var collectionView: UICollectionView!
var getUserData = ["clientType" : "2", "docType" : "002","docNum": "16191725","email": "corp.admin@postpago.com","msisdn": "914171620"]
var purchases : NSArray = []
struct MobileLines {
let name:String
let benefit:String
let price:String
let expiration:String
init?(_ dict:[String:Any]?) {
guard let _dict = dict,
let name = _dict["name"] as? String,
let benefit = _dict["benefit"] as? String,
let price = _dict["price"] as? String,
let expiration = _dict["expiration"] as? String
else { return nil }
self.name = name
self.benefit = benefit
self.price = price
self.expiration = expiration
}
}
var arrMobileLines = [MobileLines]()
func getPurchases (_ userData: NSDictionary) {
let url = URL(string: "http://162.209.99.39:8080/MiClaroBackend/purchase/mobile/MobilePostpaidActive-51914171620/products?type=voice")
let session = URLSession.shared
let request = NSMutableURLRequest(url: url!)
request.httpMethod = "POST"
self.getUserData = userData as! [String : String]
let paramToSend = ["userData":userData]
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try! JSONSerialization.data(withJSONObject: paramToSend)
let task = session.dataTask(with: request as URLRequest, completionHandler: {
(data, response, error) in
guard let _:Data = data else
{
return
}
let json:AnyObject?
do {
json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
if let parseJSON = json{
let purchaseProducts = parseJSON["purchaseProducts"] as! NSArray
self.purchases = purchaseProducts
print(json!)
}
} catch {
}
})
task.resume()
}
}
extension CategoryRow : UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.arrMobileLines.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "videoCell", for: indexPath) as! VideoCell
self.arrMobileLines = self.purchases.flatMap({ MobileLines($0 as? [String:Any])})
let dataAtIndex = self.arrMobileLines[indexPath.row]
cell.name.text = String(dataAtIndex.name)
return cell
}
}
extension CategoryRow : UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let itemsPerRow:CGFloat = 4
let hardCodedPadding:CGFloat = 5
let itemWidth = (collectionView.bounds.width / itemsPerRow) - hardCodedPadding
let itemHeight = collectionView.bounds.height - (2 * hardCodedPadding)
return CGSize(width: itemWidth, height: itemHeight)
}
}
CollectionViewCell只有一个标签:
import UIKit
class VideoCell : UICollectionViewCell {
@IBOutlet weak var name: UILabel!
}
最后我有一个ViewController,其中调用REST API的方法是在ViewDidLoad()中实现的:
class ViewController: UIViewController {
var categories = ["Action", "Drama", "Science Fiction", "Kids", "Horror"]
var categoryRow = CategoryRow()
override func viewDidLoad() {
super.viewDidLoad()
categoryRow.getPurchases(categoryRow.getUserData as NSDictionary)
}
}
extension ViewController : UITableViewDelegate { }
extension ViewController : UITableViewDataSource {
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return categories[section]
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! CategoryRow
return cell
}
}
这就是故事板的样子:
最后这是应用程序显示的内容(无):
正如您在下面的图片中看到的那样,App正在返回WS数组,因此这不是问题所在。另一个奇怪的事情是,当它应该是红色时,细胞的背景显得很黑。