在这里,你将会学习到解析JSON数据,网络请求功能,动态调整cell内容等功能!!!
最终的结果 是这样的,项目相对简单,很适合入门!下面让我们一起开始教程之旅吧!
1、先看下项目工程结构:
第一步:创建Utitlities文件夹,先完成基础通用的辅助功能
1、网络请求类:HttpRequest.swift
- import Foundation
-
- class HttpRequest: NSObject {
- override init() {
- super.init()
- }
-
-
-
-
-
-
- class func parseJSONData(data: AnyObject?) ->NSDictionary? {
- if let downloadData: NSData = data as? NSData {
- var jsonData: AnyObject? = NSJSONSerialization.JSONObjectWithData(downloadData,
- options: NSJSONReadingOptions.MutableContainers,
- error: nil) as? NSDictionary
-
- return jsonData as? NSDictionary
- }
-
-
- return nil
- }
-
-
-
-
-
-
-
- class func request(#urlString: String?, completion: (data: NSDictionary?) ->Void) {
- if urlString == nil {
- dispatch_async(dispatch_get_main_queue(), { () -> Void in
- println("urlstring 为空")
-
- completion(data: nil)
- })
- return
- }
-
- let url = NSURL.URLWithString(urlString!)
- let request = NSURLRequest(URL: url)
-
- let queue = NSOperationQueue()
- NSURLConnection.sendAsynchronousRequest(request, queue: queue) {
- (response, data, error) -> Void in
- if error != nil {
- dispatch_async(dispatch_get_main_queue(), { () -> Void in
- println(error)
-
- completion(data: nil)
- })
- } else {
- let parseData = self.parseJSONData(data)
-
- dispatch_async(dispatch_get_main_queue(), { () -> Void in
- completion(data: parseData)
- })
- }
- }
- }
- }
2、对String的扩展:
- import Foundation
- import UIKit
-
- extension String {
-
-
-
-
-
-
- func height(let fontSize: CGFloat, let width: CGFloat) ->CGFloat {
- let font = UIFont.systemFontOfSize(fontSize)
- let size = CGSizeMake(width, CGFloat.max)
-
- var style = NSMutableParagraphStyle()
- style.lineBreakMode = NSLineBreakMode.ByCharWrapping
-
- var attributes = [NSFontAttributeName: font, NSParagraphStyleAttributeName: style.copy()];
-
-
- var text = self as NSString
- var rect = text.boundingRectWithSize(size,
- options: NSStringDrawingOptions.UsesLineFragmentOrigin,
- attributes: attributes,
- context: nil)
-
- return rect.size.height
- }
-
-
-
-
-
-
- func dateStringFromTimeStamp(let timeStamp: NSString) ->String {
- var formatter = NSDateFormatter()
- formatter.dateFormat = "yyyy年MM月dd日 HH:MM:ss"
-
- let date = NSDate(timeIntervalSince1970: timeStamp.doubleValue)
- return formatter.stringFromDate(date)
- }
- }
3、UIView扩展:
- import Foundation
- import UIKit
-
- extension UIView {
-
-
-
- func originX() ->CGFloat {
- return self.frame.origin.x
- }
-
- func originX(let originX: CGFloat) {
- var rect = self.frame
- rect.origin.x = originX
- self.frame = rect
- }
-
-
-
-
- func originY() ->CGFloat {
- return self.frame.origin.y
- }
-
- func originY(let originY: CGFloat) {
- var rect = self.frame
- rect.origin.y = originY
- self.frame = rect
- }
-
-
-
-
- func origin() ->CGPoint {
- return self.frame.origin
- }
-
- func origin(let origin: CGPoint) {
- var rect = self.frame
- rect.origin = origin
- self.frame = rect
- }
-
-
-
-
- func width() ->CGFloat {
- return self.frame.size.width
- }
-
- func width(let width: CGFloat) {
- var rect = self.frame
- rect.size.width = width
- self.frame = rect
- }
-
-
-
-
- func height() ->CGFloat {
- return self.frame.size.height
- }
-
- func height(let height: CGFloat) {
- var rect = self.frame
- rect.size.height = height
- self.frame = rect
- }
-
-
-
-
- func rightX() ->CGFloat {
- return originX() + width()
- }
-
-
-
-
- func bottomY() ->CGFloat {
- return originY() + height()
- }
-
- func bottomY(let bottomY: CGFloat) {
- var rect = self.frame
- rect.origin.y = bottomY - height()
- self.frame = rect
- }
- }
第二步:分析好项目的特性,这几个显示的内容格式很像,因此这里使用了同一个基类,这也需要我们先封装一个基类:
BaseRefreshController
- class BaseRefreshController: UIViewController,
- UITableViewDataSource,
- UITableViewDelegate,
- RefreshViewDelegate,
- JokerCellDelegate {
- var refreshView: RefreshView?
- var dataSource = NSMutableArray()
- var tableView: UITableView?
- var currentPage: Int = 1
- var cellIdentifier = "JokerCellIdentifier"
-
- override func viewDidLoad() {
- super.viewDidLoad()
-
- self.automaticallyAdjustsScrollViewInsets = false;
- self.view.backgroundColor = UIColor.whiteColor()
-
- self.tableView = UITableView(frame: CGRectMake(0, 64, self.view.width(), kScreenHeight - 49 - 64))
- self.tableView?.dataSource = self
- self.tableView?.delegate = self
- self.tableView?.separatorStyle = UITableViewCellSeparatorStyle.None
- self.view.addSubview(self.tableView!)
- var nib = UINib(nibName: "JokerCell", bundle: nil)
- self.tableView!.registerNib(nib, forCellReuseIdentifier: cellIdentifier)
-
-
- var array = NSBundle.mainBundle().loadNibNamed("RefreshView", owner: self, options: nil) as Array
- self.refreshView = array[0] as? RefreshView
- self.tableView!.tableFooterView = self.refreshView
- self.refreshView!.delegate = self
- }
-
-
-
-
- func downloadData(#urlString: String) {
- let url = "\(urlString)\(self.currentPage)"
-
- self.refreshView!.startLoadingMore()
-
- HttpRequest.request(urlString: url) { (data) -> Void in
- if data == nil {
- UIAlertView.show(title: "温馨提示", message: "加载失败!")
- } else {
- var itemArray = data?["items"] as NSArray
-
- for item: AnyObject in itemArray {
- self.dataSource.addObject(item)
- }
-
- self.tableView!.reloadData()
- self.refreshView!.stopLoadingMore()
- self.currentPage++
- }
- }
- }
-
-
-
-
- func numberOfSectionsInTableView(tableView: UITableView) -> Int {
- return 1
- }
-
- func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
- return self.dataSource.count
- }
-
- func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
- var cell = tableView.dequeueReusableCellWithIdentifier(self.cellIdentifier, forIndexPath: indexPath) as? JokerCell
-
- cell?.delegate = self
-
- if indexPath.row < self.dataSource.count {
- var dataDict = self.dataSource[indexPath.row] as NSDictionary
- cell?.data = dataDict
- }
-
- return cell!
- }
-
-
-
-
- func tableView(tableView: UITableView!, heightForRowAtIndexPath indexPath: NSIndexPath!) -> CGFloat {
- var index = indexPath.row
- var data = self.dataSource[index] as NSDictionary
-
- return JokerCell.cellHeight(data)
- }
-
- func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
- var index = indexPath.row
- var data = self.dataSource[index] as NSDictionary
-
- let comment = CommentController()
- comment.jokeId = data["id"] as? String
- self.navigationController?.pushViewController(comment, animated: true)
- }
-
-
-
-
- func jokerCell(cell: JokerCell, didClickPicture picutre: String) {
- let browser = PhotoBrowserController()
- browser.bigImageUrlString = picutre
- self.navigationController?.pushViewController(browser, animated: true)
- }
- }
如果使用的cell不一样,那么子类需要重写对应的代理方法,像查看评论这个就需要重写:
CommentController:
- import UIKit
-
- class CommentController: BaseRefreshController {
-
- var jokeId: String?
-
- override func viewDidLoad() {
- super.viewDidLoad()
-
- self.title = "评论"
- var nib = UINib(nibName: "CommentCell", bundle: nil)
- self.tableView!.registerNib(nib, forCellReuseIdentifier: "CommentCellIdentifier")
- self.tableView!.height(kScreenHeight - 64)
- }
-
- override func viewWillAppear(animated: Bool) {
- super.viewWillAppear(animated)
-
- if let root = self.tabBarController as? RootTabBarController {
- root.tabBarView?.hidden = true
- }
-
- if self.jokeId != nil {
- downloadData(urlString: "http://m2.qiushibaike.com/article/\(self.jokeId!)/comments?count=20&page=")
- }
- }
-
- override func viewWillDisappear(animated: Bool) {
- super.viewWillDisappear(animated)
-
-
- if let root = self.tabBarController as? RootTabBarController {
- root.tabBarView?.hidden = false
- }
- }
-
-
-
- func refresh(refreshView: RefreshView, didClickButton button: UIButton) {
- if self.jokeId != nil {
- downloadData(urlString: "http://m2.qiushibaike.com/article/\(self.jokeId!)/comments?count=20&page=")
- }
- }
-
-
-
-
- override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
- var cell = tableView.dequeueReusableCellWithIdentifier("CommentCellIdentifier", forIndexPath: indexPath) as? CommentCell
-
- if indexPath.row < self.dataSource.count {
- var dataDict = self.dataSource[indexPath.row] as NSDictionary
- cell?.data = dataDict
- }
-
-
- return cell!
- }
-
-
-
-
- override func tableView(tableView: UITableView!, heightForRowAtIndexPath indexPath: NSIndexPath!) -> CGFloat {
- var index = indexPath.row
- var data = self.dataSource[index] as NSDictionary
-
- return CommentCell.cellHeight(data)
- }
-
- override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
-
- }
- }
这样封装好以后,下面的最新、热门、真相这三个模块就很简化了:
- import Foundation
- import UIKit
-
- class HotController: BaseRefreshController {
-
-
-
- override func viewDidLoad() {
- super.viewDidLoad()
-
- self.title = "热门";
- downloadData(urlString: "http://m2.qiushibaike.com/article/list/suggest?count=20&page=")
- }
-
-
-
- func refresh(refreshView: RefreshView, didClickButton button: UIButton) {
- downloadData(urlString: "http://m2.qiushibaike.com/article/list/suggest?count=20&page=")
- }
- }
- import Foundation
- import UIKit
-
- class LatestController: BaseRefreshController {
-
-
-
- override func viewDidLoad() {
- super.viewDidLoad()
-
- self.title = "最新";
- downloadData(urlString: "http://m2.qiushibaike.com/article/list/latest?count=20&page=")
- }
-
-
-
- func refresh(refreshView: RefreshView, didClickButton button: UIButton) {
- downloadData(urlString: "http://m2.qiushibaike.com/article/list/latest?count=20&page=")
- }
- }
- import Foundation
- import UIKit
-
- class TruthController: BaseRefreshController {
-
-
-
- override func viewDidLoad() {
- super.viewDidLoad()
-
- self.title = "真相";
- downloadData(urlString: "http://m2.qiushibaike.com/article/list/imgrank?count=20&page=")
- }
-
-
-
- func refresh(refreshView: RefreshView, didClickButton button: UIButton) {
- downloadData(urlString: "http://m2.qiushibaike.com/article/list/imgrank?count=20&page=")
- }
- }
那么剩下定制cell及动态调整内容就让大家自己去查看源码了!!!!!
想要源码吗?猛击这里
版权声明:本文为博主原创文章,未经博主允许不得转载。