import UIKit
var srcW = UIScreen.main.bounds.size.width
var srcH = UIScreen.main.bounds.size.height
class NewsViewController:BaseViewController,UITableViewDelegate,UITableViewDataSource {
//MARK:-----------------定义属性----------------
//表格
var tbv:UITableView?
//表格的数组
var tbvData:[News]?
//分段控制器
var segment:UISegmentedControl?
//标题数据
var titles = ["商会动态","时政动态","平远新闻","博风雅颂"]
//下拉刷新控件
var mjHeader:MJRefreshHeaderView?
//MARK:-----------------------UI创建-----------------------------
func initUI() -> Void {
//标题分段控件
self.segment = UISegmentedControl.init(items: titles)
self.segment?.frame = CGRect.init(x: 0, y: 64, width: srcW, height: 40)
//设置默认分段控制器的下标
self.segment?.selectedSegmentIndex = 0
self.segment?.tintColor = UIColor.gray
//添加事件
self.segment?.addTarget(self, action: #selector(titleSegDidChange(seg:)), for: UIControl.Event.valueChanged)
//将分段控制器器添加为view的子视图
self.view.addSubview(self.segment!)
//表格视图
self.tbv = UITableView.init(frame: CGRect.init(x: 0, y: 104, width: srcW, height: srcH - 104), style: .plain)
self.tbv?.delegate = self
self.tbv?.dataSource = self
self.view.addSubview(self.tbv!)
}
//MARK:-----------------------UITableView-----------------------------
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//创建一个详情控制器
let detailVC = DetailViewController()
//通过选中的单元格的下标获取对应的News对象
if let selectNew = self.tbvData?[indexPath.row]{
detailVC.passNews = selectNew
}
//跳转至详情控制器
self.navigationController?.pushViewController(detailVC, animated: true)
}
//MARK:-----------------------UI触发事件-----------------------------
@objc func titleSegDidChange(seg:UISegmentedControl) -> Void {
//要根据选中的标题的下标获取不同的新闻数据
self.getURLData(titleIndex: seg.selectedSegmentIndex)
}
//MARK:-----------------------获取网络数据-----------------------------
func getURLData(titleIndex:Int) -> Void {
//转动指示器
UIApplication.shared.isNetworkActivityIndicatorVisible = true
//网络请求,网址字符串拼接
let urlStr = "http://py.cmshop.net/tPyshNewnoticController.do?godongtai2&style2=\(titleIndex)"
//转换URL地址
let url = URL.init(string: urlStr)
//请求对象,并设置缓存策略和超时时长
let req = URLRequest.init(url: url!, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 8.0)
//连接服务器任务
let task = URLSession.shared.dataTask(with: req) { (data, response, error) in
//停止转动等待指示器
DispatchQueue.main.async {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
//停止下拉刷新控件
self.mjHeader?.endRefreshing()
}
//如果服务器连接失败或超时
if error != nil{
DispatchQueue.main.async {
self.view.showMBAlert(msg: "服务器错误")
}
return
}
//如果连接成功,将二进制数据转换为数组或字典
let jsonData = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments)
//如果转换失败
if jsonData == nil{
DispatchQueue.main.async {
self.view.showMBAlert(msg: "网络数据错误")
}
return
}
//转换成功,将数据强转为字典类型
let jsonDic = jsonData! as! NSDictionary
//获取resultcode值
let resultcode = jsonDic["resultcode"] as! String
//如果resultcode值不为0,表示有错误发生,给出用户提示
if resultcode != "0" {
let errmsg = jsonDic["errmsg"] as! String
DispatchQueue.main.async {
self.view.showMBAlert(msg: errmsg)
}
return
}
//如果数据都正确,做json解析
let dataArr = jsonDic["data"] as! [[String:Any]]
self.tbvData = News.createNewsArray(arr: dataArr)
//回到UI主线程刷新表格
DispatchQueue.main.async {
self.tbv?.reloadData()
}
}
task.resume()
}
//MARK:-----------------------viewDidLoad-----------------------------
override func viewDidLoad() {
super.viewDidLoad()
//创建UI
self.initUI()
//获取网络数据,字典获取第一个标题的新闻数据
self.getURLData(titleIndex: 0)
//下拉刷新控件
self.mjHeader = MJRefreshHeaderView.init(scrollView: self.tbv!)
//设置刷新回调的闭包
self.mjHeader?.beginRefreshingBlock = {refreshView in
self.getURLData(titleIndex: self.segment!.selectedSegmentIndex)
}
self.tbv?.rowHeight = 150
}
//MARK:--------------实现代理和数据源-----------------------
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let count = self.tbvData?.count{
return count
}
return 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let identifier = "MyCell"
var cell = tableView.dequeueReusableCell(withIdentifier: identifier) as? NewsTableViewCell
if cell == nil{
cell = NewsTableViewCell.init(style: .subtitle, reuseIdentifier: identifier)
}
//根据下标获取该行对应的News对象
if let one = self.tbvData?[indexPath.row]{
cell?.imgView?.sd_setImage(with: URL.init(string: "http://py.cmshop.net/\(one.uploadimgurl)"), completed: nil)
cell?.titlelabel?.text = one.title
cell?.authorLable?.text = "作者:\(one.createName)"
//把时间戳值获取
let seconds = one.createDate
//把时间戳转换为时间对象
let date = Date.init(timeIntervalSince1970:TimeInterval(seconds/1000))
//实力换一个日期格式器对象
let dateFormate = DateFormatter.init()
dateFormate.dateFormat = "yyyy-MM-dd HH:mm:ss"
//把日期按照格式器样式转换为字符串
let dateStr = dateFormate.string(from: date)
cell?.dateLabel?.text = dateStr
}
return cell!
}
}
网友评论