swift controlllerview

// (1) 在view中創(chuàng)建controlllerview 并且新建一個繼承controlllerviewcell的類 兩個繼承nsobject類一個做model一個做請求數(shù)據(jù)的類

import UIKit


class ViewController: UIViewController ,UICollectionViewDelegate,UICollectionViewDataSource{


? ? var readID = "readID"


? ? var flowlayout = UICollectionViewFlowLayout()

? ? var collection: UICollectionView?

? ? var collecArr:[SwiftModel]?

//? ? var collecArr = ["3","1","2"]


? ? override func viewDidLoad() {

? ? ? ? super.viewDidLoad()

? ? ? ? // 設置網格的大小

? ? ? ? flowlayout.itemSize = CGSize(width:self.view.frame.size.width/4, height: 100)

? ? ? ? //設置最小行間距

? ? ? ? flowlayout.minimumLineSpacing = 1


? ? ? ? //設置最小列間距

? ? ? ? flowlayout.minimumInteritemSpacing = 40


? ? ? ? //設置分區(qū)縮進量

? ? ? ? flowlayout.sectionInset = UIEdgeInsets(top: 20, left: 10, bottom: 20, right: 10)



? ? ? ? // 設置滾動方向

? ? ? ? flowlayout.scrollDirection = UICollectionViewScrollDirection.vertical


? ? ? ? // 網格對象

? ? ? ? collection = UICollectionView(frame:CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height) , collectionViewLayout: flowlayout)

? ? ? ? // 設置代理協(xié)議

? ? ? ? collection?.delegate = self

? ? ? ? collection?.dataSource = self

? ? ? ? collection?.backgroundColor = UIColor.blue

? ? ? ? collection?.register(NewsCollectionViewCell? .self, forCellWithReuseIdentifier: readID)


? ? ? ? // 添加網格

? ? ? ? self.view .addSubview(collection!)


? ? }

// 實現(xiàn)網格的協(xié)議代理

? ? func numberOfSections(in collectionView: UICollectionView) -> Int {

? ? ? ? return 4

? ? }

? ? func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

//? ? ? ? return collecArr.count

? ? ? ? return 6

? ? }


? ? func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

? ? ? ? // 重用cell

? ? ? ? let cell:NewsCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: readID, for: indexPath) as! NewsCollectionViewCell


? ? ? ? if self.collecArr != nil{

? ? ? ? ? ? let dic = self.collecArr![indexPath.item]


? ? ? ? ? ? cell.titlelabel?.text = dic.title

? ? ? ? }




? ? ? ? return cell


? ? }



? ? override func viewWillAppear(_ animated: Bool) {

? ? ? ? super.viewWillAppear(animated)


? ? ? ? self.requestNetWorlDataAndUpdata()

? ? }

? ? func requestNetWorlDataAndUpdata() -> Void {

? ? ? ? // 轉動菊花

? ? ? ? UIApplication.shared.isNetworkActivityIndicatorVisible = true


? ? ? ? // 請求網絡數(shù)據(jù)

? ? ? ? let urlService = Network()

? ? ? ? urlService.getNewsData(channel: "頭條", startSum: 0) { (data, success) in

? ? ? ? ? ? // 停止指示器

? ? ? ? ? ? DispatchQueue.main.async {

? ? ? ? ? ? ? ? UIApplication.shared.isNetworkActivityIndicatorVisible = false


? ? ? ? ? ? }


? ? ? ? ? ? // 如果不成功

? ? ? ? ? ? if !success{

? ? ? ? ? ? ? ? // 異步執(zhí)行

? ? ? ? ? ? ? ? DispatchQueue.main.async {

? ? ? ? ? ? ? ? ? ? let alertVC = UIAlertController(title: nil, message: data as? String, preferredStyle: .alert)

? ? ? ? ? ? ? ? ? ? let confirmBtn = UIAlertAction(title: "確定", style: .default, handler: nil)

? ? ? ? ? ? ? ? ? ? alertVC.addAction(confirmBtn)

? ? ? ? ? ? ? ? ? ? self.present(alertVC, animated: true, completion: {


? ? ? ? ? ? ? ? ? ? })


? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? return

? ? ? ? ? ? }


? ? ? ? ? ? self.collecArr = data as? [SwiftModel]

? ? ? ? ? ? print(self.collecArr)

? ? ? ? ? ? DispatchQueue.main.async {

? ? ? ? ? ? ? ? self.collection?.reloadData()

? ? ? ? ? ? }

? ? ? ? }

? ? }

? ? }

(2) ?model里的代碼


class SwiftModel: NSObject {

? ? var time:String = ""

? ? var title:String = ""

? ? var pic:String = ""

? ? var content:String = ""

? ? var weburl:String = ""

}

(3) 請求數(shù)據(jù)


import UIKit


class Network: NSObject {

? ? func getNewsData(channel:String,startSum:Int,complation:@escaping (Any,Bool) -> Void) -> Void {

? ? ? ? // get 請求網絡數(shù)據(jù)

? ? ? ? // (1) 網址字符串拼接

? ? ? ? var urlStr = "http://api.jisuapi.com/news/get?channel=\(channel)&start=\(startSum)&num=10&appkey=de394933e1a3e2db"

? ? ? ? // (2) 轉碼

? ? ? ? urlStr = urlStr.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlFragmentAllowed)!

? ? ? ? // (3) 分裝為URL對象

? ? ? ? let url = URL(string: urlStr)

? ? ? ? // (4) 分裝為urlrequest對象

? ? ? ? let req = URLRequest(url: url!, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 10.0)

? ? ? ? // (5) 使用urlsession請求網絡數(shù)據(jù)

? ? ? ? let task:URLSessionDataTask = URLSession.shared.dataTask(with: req) { (data, response, error) in

? ? ? ? ? ? // 如果發(fā)生錯誤

? ? ? ? ? ? if error != nil{

? ? ? ? ? ? ? ? // 參數(shù)閉包的調用

? ? ? ? ? ? ? ? complation("網絡服務錯誤",false)

? ? ? ? ? ? ? ? return

? ? ? ? ? ? }

? ? ? ? ? ? // json 數(shù)據(jù)解析

? ? ? ? ? ? let jsonData = try? JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments)

? ? ? ? ? ? // json 解析失敗 返回錯誤

? ? ? ? ? ? if jsonData == nil{

? ? ? ? ? ? ? ? complation("網絡數(shù)據(jù)錯誤",false)

? ? ? ? ? ? ? ? return

? ? ? ? ? ? }

? ? ? ? ? ? let status = (jsonData as! NSDictionary) .value(forKey: "status")as! String

? ? ? ? ? ? let msg = (jsonData as! NSDictionary).value(forKey: "msg") as! String


? ? ? ? ? ? if Int(status)! != 0{

? ? ? ? ? ? ? ? complation(msg,false)

? ? ? ? ? ? ? ? return

? ? ? ? ? ? }


? ? ? ? ? ? let result = (jsonData as! NSDictionary).value(forKey: "result") as! NSDictionary


? ? ? ? ? ? let list = (result.value(forKey: "list") as! NSArray)


? ? ? ? ? ? var arr:[SwiftModel] = []


? ? ? ? ? ? for item in list{

? ? ? ? ? ? ? ? let dic = (item as! NSDictionary)

? ? ? ? ? ? ? ? let oneNew = SwiftModel()

? ? ? ? ? ? ? ? oneNew.title = dic.value(forKey: "title") as! String

? ? ? ? ? ? ? ? oneNew.content = dic.value(forKey: "content") as! String

? ? ? ? ? ? ? ? oneNew.time = dic.value(forKey: "time") as! String

? ? ? ? ? ? ? ? oneNew.pic = dic.value(forKey: "pic") as! String

? ? ? ? ? ? ? ? oneNew.weburl = dic.value(forKey: "weburl") as! String

? ? ? ? ? ? ? ? print(oneNew.title)

? ? ? ? ? ? ? ? arr.append(oneNew)

? ? ? ? ? ? }

? ? ? ? ? ? complation(arr,true)



? ? ? ? }

? ? ? ? // (6)開啟任務

? ? ? ? task .resume()



? ? }

}

(7) controllerviewcell中的代碼

import UIKit


class NewsCollectionViewCell: UICollectionViewCell {

? ? // 創(chuàng)建兩個label

? ? var? titlelabel:UILabel?

? ? var handlabel:UILabel?

? ? override init(frame: CGRect) {

? ? ? ? super .init(frame: frame)

? ? ? ? self.titlelabel = UILabel()

? ? ? ? self.addSubview(titlelabel!)

? ? ? ? self.handlabel = UILabel()

? ? ? ? self.addSubview(handlabel!)

? ? ? ? setTitle()

? ? ? ? sethand()

? ? }

? ? func setTitle(){

? ? ? ? self.titlelabel?.frame = CGRect(x: 0, y: 0, width: self.frame.size.width, height: 20)

? ? ? ? self.titlelabel?.font = UIFont .systemFont(ofSize: 14.0)

? ? ? ? self.titlelabel?.backgroundColor = UIColor.red

? ? ? ? self.titlelabel?.numberOfLines = 0

? ? }

? ? func sethand()? {

? ? ? ? self.handlabel?.frame = CGRect(x: 0, y: 20, width: self.frame.size.width, height: 80)

? ? ? ? self.handlabel?.font = UIFont .systemFont(ofSize: 12.0)

? ? ? ? self.handlabel?.backgroundColor = UIColor.green

? ? ? ? self.handlabel?.numberOfLines = 0

? ? }

? ? required init?(coder aDecoder: NSCoder) {

? ? ? ? fatalError("init(coder:) has not been implemented")

? ? }


}

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容