AppDelegate.swift
funcapplication(_application:UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey:Any]?) ->Bool{
letnewsVC =NewsViewController()
letnewsNav =UINavigationController.init(rootViewController: newsVC)
newsNav.tabBarItem=UITabBarItem.init(title:"新闻", image:UIImage.init(), tag:1)
newsNav.navigationBar.barTintColor = UIColor.orange
newsVC.navigationItem.title = "我的新闻"
let collVC = CollectViewController()
letcollNav =UINavigationController.init(rootViewController: collVC)
collNav.tabBarItem=UITabBarItem.init(title:"收藏", image:UIImage.init(named:""), tag:1)
collNav.navigationBar.barTintColor = UIColor.orange
collVC.navigationItem.title = "我的收藏"
let tbc = UITabBarController()
tbc.viewControllers= [newsNav,collNav]
self.window?.rootViewController = tbc
return true
}
UIViewExtension.swift
extension UIView{
//显示MB提示框
funcshowMBAlert(msg:String) ->Void{
//实例化MB
letalert = MBProgressHUD.init(view:self)
//设置为文本提示样式
alert?.mode = MBProgressHUDModeText
//设置隐藏时自动从父视图移除
alert?.removeFromSuperViewOnHide =true
//设置显示的提示文本
alert?.labelText = msg
//添加为子视图
self.addSubview(alert!)
//显示提示框
alert?.show(true)
//2.5秒后自动隐藏
alert?.hide(true, afterDelay:2.5)
}
}
News.swift
class News:NSObject {
varaccountid ="" //用户
varcreateDate =0 //创建时间
varcreateName ="" //创建人名称
varid ="" //新闻的ID
varstyle ="" //新闻的总分类
varstyle2 ="" //新闻的二级分类
vartitle ="" //标题
vartxturl ="" //详情地址
varupdateName ="" //更新时间
varuploadimgurl ="" //图片地址
///类方法,用于把一个字典数组转换为News数组
static funccreateNewsArray(arr:[[String:Any]]) -> [News] {
//创建一个可变的News数组
varnewsArr:[News] = []
fordicinarr{
letone =News()
// one.setValuesForKeys(dic)
one.title= dic["title"]!as!String
one.txturl= dic["txturl"]!as!String
one.createDate= dic["createDate"]as!Int
one.createName= dic["createName"]as!String
one.uploadimgurl= dic["uploadimgurl"]as!String
newsArr.append(one)
}
returnnewsArr
}
overridefuncsetValue(_value:Any?, forUndefinedKey key:String) {
print("没有定义的属性\(key),值\(value)")
}
}
NewsTableViewCell.swift
classNewsTableViewCell:UITableViewCell{
//MARK:------------------UI控件-----------------------
varimgView:UIImageView?//图片视图
vartitlelabel:UILabel? //标题标签
vardateLabel:UILabel? //时间标签
varauthorLable:UILabel? //作者标签
//创建UI控件
funcinitUI() {
//图片视图
self.imgView=UIImageView.init(frame:CGRect.init(x:5, y:5, width:140, height:140))
self.contentView.addSubview(self.imgView!)
//标题标签
self.titlelabel=UILabel.init(frame:CGRect.init(x:150, y:5, width:srcW-155, height:100))
self.titlelabel?.font=UIFont.systemFont(ofSize:20.0)
self.titlelabel?.numberOfLines=3
self.contentView.addSubview(self.titlelabel!)
//时间标签
self.dateLabel=UILabel.init(frame:CGRect.init(x:250, y:125, width:srcW-200, height:13))
self.dateLabel?.font=UIFont.systemFont(ofSize:14.0)
self.dateLabel?.textColor = UIColor.lightGray
self.contentView.addSubview(self.dateLabel!)
//作者标签
self.authorLable=UILabel.init(frame:CGRect.init(x:150, y:125, width:150, height:13))
self.authorLable?.font=UIFont.systemFont(ofSize:14.0)
self.authorLable?.textColor = UIColor.lightGray
self.contentView.addSubview(self.authorLable!)
}
//MARK:------------------init-----------------------
overrideinit(style:UITableViewCell.CellStyle, reuseIdentifier:String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.initUI()
}
requiredinit?(coder aDecoder:NSCoder) {
fatalError("init(coder:) has not been implemented")
}
overridefuncawakeFromNib() {
super.awakeFromNib()
// Initialization code
}
overridefuncsetSelected(_selected:Bool, animated:Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
NewsViewController.swift
var srcW = UIScreen.main.bounds.size.width
var srcH = UIScreen.main.bounds.size.height
class NewsViewController:BaseViewController,UITableViewDelegate,UITableViewDataSource {
//MARK:-----------------定义属性----------------
//表格
var tbv:UITableView?
//表格的数组
vartbvData:[News]?
//分段控制器
var segment:UISegmentedControl?
//标题数据
var titles = ["商会动态","时政动态","平远新闻","博风雅颂"]
//下拉刷新控件
var mjHeader:MJRefreshHeaderView?
//MARK:-----------------------UI创建-----------------------------
funcinitUI() ->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-----------------------------
functableView(_tableView:UITableView, didSelectRowAt indexPath:IndexPath) {
//创建一个详情控制器
letdetailVC =DetailViewController()
//通过选中的单元格的下标获取对应的News对象
ifletselectNew =self.tbvData?[indexPath.row]{
detailVC.passNews= selectNew
}
//跳转至详情控制器
}
//MARK:-----------------------UI触发事件-----------------------------
@objcfunctitleSegDidChange(seg:UISegmentedControl) ->Void{
//要根据选中的标题的下标获取不同的新闻数据
self.getURLData(titleIndex: seg.selectedSegmentIndex)
}
//MARK:-----------------------获取网络数据-----------------------------
funcgetURLData(titleIndex:Int) ->Void{
//转动指示器
UIApplication.shared.isNetworkActivityIndicatorVisible = true
//网络请求,网址字符串拼接
let urlStr = "http://py.cmshop.net/tPyshNewnoticController.do?godongtai2&style2=\(titleIndex)"
//转换URL地址
leturl =URL.init(string: urlStr)
//请求对象,并设置缓存策略和超时时长
letreq =URLRequest.init(url: url!, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval:8.0)
//连接服务器任务
lettask =URLSession.shared.dataTask(with: req) { (data, response, error)in
//停止转动等待指示器
DispatchQueue.main.async {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
//停止下拉刷新控件
self.mjHeader?.endRefreshing()
}
//如果服务器连接失败或超时
iferror !=nil{
DispatchQueue.main.async {
self.view.showMBAlert(msg:"服务器错误")
}
return
}
//如果连接成功,将二进制数据转换为数组或字典
letjsonData =try? JSONSerialization.jsonObject(with: data!, options: .allowFragments)
//如果转换失败
ifjsonData ==nil{
DispatchQueue.main.async {
self.view.showMBAlert(msg:"网络数据错误")
}
return
}
//转换成功,将数据强转为字典类型
letjsonDic = jsonData!as!NSDictionary
//获取resultcode值
letresultcode = jsonDic["resultcode"]as!String
//如果resultcode值不为0,表示有错误发生,给出用户提示
ifresultcode !="0"{
leterrmsg = jsonDic["errmsg"]as!String
DispatchQueue.main.async {
self.view.showMBAlert(msg: errmsg)
}
return
}
//如果数据都正确,做json解析
letdataArr = jsonDic["data"]as! [[String:Any]]
self.tbvData=News.createNewsArray(arr: dataArr)
//回到UI主线程刷新表格
DispatchQueue.main.async {
self.tbv?.reloadData()
}
}
task.resume()
}
//MARK:-----------------------viewDidLoad-----------------------------
overridefuncviewDidLoad() {
super.viewDidLoad()
//创建UI
self.initUI()
//获取网络数据,字典获取第一个标题的新闻数据
self.getURLData(titleIndex:0)
//下拉刷新控件
self.mjHeader = MJRefreshHeaderView.init(scrollView:self.tbv!)
//设置刷新回调的闭包
self.mjHeader?.beginRefreshingBlock = {refreshViewin
self.getURLData(titleIndex:self.segment!.selectedSegmentIndex)
}
self.tbv?.rowHeight=150
}
//MARK:--------------实现代理和数据源-----------------------
functableView(_tableView:UITableView, numberOfRowsInSection section:Int) ->Int{
ifletcount =self.tbvData?.count{
returncount
}
return0
}
functableView(_tableView:UITableView, cellForRowAt indexPath:IndexPath) ->UITableViewCell{
letidentifier ="MyCell"
varcell = tableView.dequeueReusableCell(withIdentifier: identifier)as?NewsTableViewCell
ifcell ==nil{
cell =NewsTableViewCell.init(style: .subtitle, reuseIdentifier: identifier)
}
//根据下标获取该行对应的News对象
ifletone =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)"
//把时间戳值获取
letseconds = one.createDate
//把时间戳转换为时间对象
letdate =Date.init(timeIntervalSince1970:TimeInterval(seconds/1000))
//实力换一个日期格式器对象
letdateFormate =DateFormatter.init()
dateFormate.dateFormat="yyyy-MM-dd HH:mm:ss"
//把日期按照格式器样式转换为字符串
letdateStr = dateFormate.string(from: date)
cell?.dateLabel?.text= dateStr
}
returncell!
}
}