oneviewconeroller
import UIKit
//屏幕的宽
var scrW = UIScreen.main.bounds.size.width
//屏幕的高
var scrH = UIScreen.main.bounds.size.height
class OneViewController: BaseViewController,UITableViewDelegate,UITableViewDataSource {
//MARK:--------------------属性的声明------------------
var tbv:UITableView?
vartbvData:[Student]?
var segment:UISegmentedControl?
var titles = ["推荐新闻","实时对话","行情分析","专栏"]
varonetitle = ["1","2","3","4"]
//下拉刷新控件
var mjHeader:MJRefreshHeaderView?
//MARK:--------------------UI创建------------------
funcinitUI() {
//创建segment分段控制器
self.segment = UISegmentedControl.init(items: titles)
//设置位置
self.segment?.frame=CGRect.init(x:0, y:0, width:scrW, height:40)
//设置默认选中的下标
self.segment?.selectedSegmentIndex = 0
//自动获取第一个标题的新闻数据
self.getURLData(titleIndex:onetitle[0])
//设置触发方法
self.segment?.addTarget(self, action:#selector(segmentDidChange(seg:)), for: .valueChanged)
self.segment?.tintColor = UIColor.black
//添加到view子视图
self.view.addSubview(self.segment!)
//实例化表格
self.tbv=UITableView.init(frame:CGRect.init(x:0, y:40, width:scrW, height:scrH-40), style: .plain)
//设置代理和数据源
self.tbv?.delegate=self
self.tbv?.dataSource=self
//添加到子视图
self.view.addSubview(self.tbv!)
//实例化下拉刷新的控件
self.mjHeader = MJRefreshHeaderView.init(scrollView:self.tbv!)
//设置刷新的回调的闭包
self.mjHeader?.beginRefreshingBlock = {refreshViewin
}
self.tbv?.rowHeight=150
}
//MARK:--------------------UI控件的触发方法------------------
@objcfuncsegmentDidChange(seg:UISegmentedControl) ->Void{
//根据选中的分段下标获取对应的标题,获取网络数据
self.getURLData(titleIndex:titles[seg.selectedSegmentIndex])
}
//MARK:-------------------viewDidLoad-------------------
overridefuncviewDidLoad() {
super.viewDidLoad()
self.initUI()
}
//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?StudentTableViewCell
ifcell ==nil{
cell =StudentTableViewCell.init(style: .subtitle, reuseIdentifier: identifier)
}
ifletoneNew =self.tbvData?[indexPath.row]{
//图片
cell?.imgview?.sd_setImage(with:URL.init(string: oneNew.img), completed:nil)
//标题
cell?.titleLabel?.text = oneNew.title
//作者
cell?.author?.text ="作者\(oneNew.author)"
//阅读量
cell?.readNum?.text ="阅读量:\(oneNew.read_num)"
}
returncell!
}
//MARK:--------------------获取网络请求数据------------------
funcgetURLData(titleIndex:String) ->Void{
//转动指示器
UIApplication.shared.isNetworkActivityIndicatorVisible = true
//网络请求,网址字符串拼接
let url = URL.init(string: "http://buluokes.huimor.com/api")
//创建请求对象,同时设置缓存策略及超时时长
varreq =URLRequest.init(url: url!, cachePolicy: .reloadRevalidatingCacheData, timeoutInterval:5.0)
//设置POST请求
req.httpMethod="POST"
//把请求参数拼接成字符串
let paramStr = "method=app.news.getarticlelist&class_id\(titleIndex)&page=1&user_token="
//将参数字符串转换为二进制Data数据
letparamData = paramStr.data(using: .utf8)
//将参数二进制数据放入请求体中
req.httpBody= paramData
//正式请求网络数据,使用URLsession
lettask =URLSession.shared.dataTask(with: req) { (data, response, error)in
//回到UI主线程停止转动指示器
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)
//如果转换失败
if jsonData ==nil{
DispatchQueue.main.async {
self.view.showMBAlert(msg:"json数据解析错误")
}
return
}
//t如果转换成功,将数据转换为字典类型
letjsonDic = jsonDataas!NSDictionary
//获取code值
letoneCode = jsonDic["code"]as!Int
//如果code的值不为200 ,表示有错误发生,给出用户提示
if oneCode !=200{
DispatchQueue.main.async {
self.view.showMBAlert(msg:"code值不是200")
}
return
}
//如果数据都正确,做JSON解析
letresultDic = jsonDic["data"]as!NSDictionary
letdataArr = resultDic["list"]as!NSArray
print(dataArr)
//将dataArr转换为News数组,赋值给表格数据数组
self.tbvData = Student.createNewsArr(withDataArr: dataArras! [Any])
//刷新表格
DispatchQueue.main.async {
self.tbv?.reloadData()
}
}
task.resume()
}
}
Student.h
#import
NS_ASSUME_NONNULL_BEGIN
@interfaceStudent :NSObject
@property(nonatomic,strong)NSString * type;
@property(nonatomic,strong)NSString * id;
@property(nonatomic,strong)NSString * img;
@property(nonatomic,strong)NSString * title;
@property(nonatomic,strong)NSString * read_num;
@property(nonatomic,strong)NSString * content;
@property(nonatomic,strong)NSString * author;
@property(nonatomic,strong)NSString * create_time;
//把得到的json数据中的data数组转换为Student数组
+(NSArray*)createNewsArrWithDataArr:(NSArray*)dataArr;
@end
NS_ASSUME_NONNULL_END
Student.m
#import "Student.h"
@implementation Student
+(NSArray*)createNewsArrWithDataArr:(NSArray*)dataArr{
//定义可变数组,用于储存Student对象
NSMutableArray * newsArr = [[NSMutableArray alloc]init];
//遍历dataArr中的每个字典
for(NSDictionary* dicindataArr){
//将每个dic转化为Student对象
Student* one = [[Studentalloc]init];
//对one的属性赋值
[onesetValuesForKeysWithDictionary:dic];
//把每次循环生成的one对象加入到数组中
[newsArraddObject:one];
}
//在循环外,将newsArr返回
return[newsArrcopy];
}
@end
AlertView.swift
import UIKit
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)
//设置几秒自动隐藏
alert?.hide(true, afterDelay:3.0)
}
}
StudentTableViewCell.swift
import UIKit
classStudentTableViewCell:UITableViewCell{
//图片视图
varimgview:UIImageView?
//标题标签
vartitleLabel:UILabel?
//作者标签
varauthor:UILabel?
//阅读量
varreadNum:UILabel?
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:145, y:5, width:scrW-155, height:50))
self.titleLabel?.font=UIFont.systemFont(ofSize:20.0)
self.contentView.addSubview(self.titleLabel!)
//作者标签
self.author=UILabel.init(frame:CGRect.init(x:145, y:80, width:150, height:40))
self.author?.font=UIFont.systemFont(ofSize:17.0)
self.author?.textColor = UIColor.gray
self.contentView.addSubview(self.author!)
//阅读量
self.readNum=UILabel.init(frame:CGRect.init(x:300, y:80, width:150, height:40))
self.readNum?.font=UIFont.systemFont(ofSize:17.0)
self.readNum?.textColor = UIColor.gray
self.contentView.addSubview(self.readNum!)
}
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
}
}
AppDelegate.swift
let oneVC = OneViewController()
letoneNav =UINavigationController.init(rootViewController: oneVC)
oneNav.tabBarItem=UITabBarItem.init(title:"新闻", image:UIImage.init(named:""), tag:1)
oneVC.navigationItem.title = "我的新闻"
lettwoVC =TwoViewController()
lettwoNav =UINavigationController.init(rootViewController: twoVC)
twoNav.tabBarItem=UITabBarItem.init(title:"娱乐", image:UIImage.init(named:""), tag:2)
twoVC.navigationItem.title = "我的娱乐"
let tbc = UITabBarController()
tbc.viewControllers= [oneNav,twoNav]
self.window?.rootViewController = tbc