Swift UI布局+读取网络数据+Swift、OC混编

Swift UI布局+读取网络数据+Swift、OC混编_第1张图片

先创建我们所要用到的文件,如:StudentsViewController MyUIViewController NewsViewController 这三个文件创建的时候语言要选择Swift; 接着创建 DetailViewController News文件 语言要选择OC,用以实现与Swift语言的混编

接着实现我们具体的代码,与OC不同,在Swift中我们要先在AppDelegate.swift中书写

class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        return true
    }

如图: 这是AppDelegate.swift中系统自带的一个类,在其中书写我们的代码, 具体如下:

class AppDelegate: UIResponder, UIApplicationDelegate {

    // 窗口对象
    var window: UIWindow?
    // 标签栏控制器
    var tabCtl : UITabBarController = UITabBarController.init()

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.

        let stuVC:StudentsViewController = StudentsViewController()
        stuVC.navigationItem.title = "学生名单"
        stuVC.view.backgroundColor  = UIColor.white
        let stuNav:UINavigationController = UINavigationController.init(rootViewController: stuVC)

        // UI
        let uiVC = MyUIViewController()
        uiVC.navigationItem.title = "控件视图"
        uiVC.view.backgroundColor  = UIColor.white

        let uiNav = UINavigationController(rootViewController: uiVC)

        // News
        let newsVC = NewsViewController()
        newsVC.navigationItem.title = "新闻头条"
        newsVC.view.backgroundColor  = UIColor.white

        let newsNav = UINavigationController(rootViewController: newsVC)

        // 给导航添加标签栏标签
        stuNav.tabBarItem = UITabBarItem.init(title: "学生", image:UIImage.init(named:"22.png"), tag: 100)

        uiNav.tabBarItem = UITabBarItem.init(tabBarSystemItem: UITabBarSystemItem.contacts, tag: 101)

        newsNav.tabBarItem = UITabBarItem.init(tabBarSystemItem: UITabBarSystemItem.bookmarks, tag: 102)

self.tabCtl.viewControllers  = [stuNav,uiNav,newsNav]

self.window?.rootViewController = self.tabCtl
return true
}

在StudentsViewController .swift中我们实现一个表格,将数组内容展示在表格中,具体代码如下:(注意Swift中一些特殊的书写格式,略与OC不同)

import UIKit

class StudentsViewController: UIViewController,UITableViewDataSource {

    var studentsData:[String]?




    override func viewDidLoad() {
        super.viewDidLoad()

        studentsData = ["小李","小王","小红","小张","小明"]

        let table:UITableView = UITableView.init(frame: self.view.frame, style: .plain)
        table.dataSource = self
        self.view.addSubview(table)

    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if let count = self.studentsData?.count{
            return count
        }
        return 0
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let str = "identifier"
        var cell = tableView.dequeueReusableCell(withIdentifier: str)

        if  cell == nil {
            cell = UITableViewCell.init(style: .default, reuseIdentifier: str)
        }
        cell?.textLabel?.text = self.studentsData?[indexPath.row]
        return cell!
    }


    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

在MyUIViewController.swift中我们用Swift实现一些简单的UI控件,代码以供参考

import UIKit

class MyUIViewController: UIViewController,UITextFieldDelegate {
    // lable控件
    var myLable:UILabel = UILabel.init(frame: CGRect(x: 20, y: 60, width: 100, height: 30))
    // button
    var myBtn:UIButton?
    // TextField
    var textFiled:UITextField?


    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
         // ===========Lable==============
        myLable.textColor = UIColor.red
        myLable.textAlignment = .center
        myLable.backgroundColor = UIColor.white
        myLable.text = "JJJJJJJJJJJJJJJJJ"
        myLable.font = UIFont.systemFont(ofSize: 17)
        self.view.addSubview(myLable)




        // ===========button==============
        myBtn = UIButton.init(type: .roundedRect)
        myBtn?.frame = CGRect(x: 20, y: 120, width: 100, height: 30)
        myBtn?.setTitle("播放", for: .normal)
        myBtn?.setTitleColor(.blue, for: .normal)

        myBtn?.setTitle("暂停", for: .selected)
        myBtn?.setTitleColor(.red, for: .selected)

        myBtn?.addTarget(self, action: #selector(btnPress(sender:)), for: .touchUpInside)
        self.view.addSubview(myBtn!)


        // ===========textField==============
        textFiled = UITextField.init(frame: CGRect(x: 20, y: 200, width: 200, height: 50))
        textFiled?.placeholder = "请输入账号"
        textFiled?.textAlignment = .center
        textFiled?.textColor = .red
        textFiled?.keyboardType = .default
        textFiled?.clearButtonMode = .whileEditing
        textFiled?.clearsOnBeginEditing = true
        textFiled?.isSecureTextEntry = false
        textFiled?.autocapitalizationType = .allCharacters
        textFiled?.borderStyle = .line
       textFiled?.delegate = self

        self.view.addSubview(textFiled!)







    }
    func btnPress(sender:UIButton) -> Void {

        sender.isSelected = !sender.isSelected
    }
    override func touchesBegan(_ touches: Set, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
        self.view.endEditing(true)
    }
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {

        textFiled?.resignFirstResponder()
        return true
    }
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        // 获取目前textField控件中的文本内容
        var text = textField.text
        // 现在文本框 的内容
        //获取目前textfield控件中的文本
        var newString = (textField.text! as NSString).replacingCharacters(in: range, with: string)

        return newString.characters.count <= 8





    }





    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

此段代码中 按钮实现了点击切换的功能 类似音乐按钮的点击播放 暂停

**

重点来了!!!!!!!!!!!!**

在NewsViewController.swift 中,我们采用json解析 实现了从网络获取新闻数据并解析最后展示在表格上,数据来自极速数据。
具体代码 :

import UIKit

class NewsViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {

    var datas:Array?
    var tableView:UITableView?

    // =========    表格协议 =======
    func tableView(_ tableView:UITableView, numberOfRowsInSection section :Int) -> Int {
        if let count = datas?.count{
            return count
        }
        return 0
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let iderfier = "cell"
        var cell = tableView.dequeueReusableCell(withIdentifier: iderfier)

        if cell == nil{
            cell = UITableViewCell.init(style: .subtitle, reuseIdentifier: iderfier)
            }
         let  oneNew = self.datas![indexPath.row]
        cell?.textLabel?.text = oneNew.title
        cell?.detailTextLabel?.text = oneNew.time

        return cell!

    }


    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let oneNews = self.datas![indexPath.row]

        let detailVc = DetailViewController()

        detailVc.detailUrl = oneNews.weburl

        self.navigationController?.pushViewController(detailVc, animated: true)

    }

  override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.getURLDatas()
    }


    override func viewDidLoad() {
        super.viewDidLoad()

        tableView = UITableView.init(frame: self.view.frame, style: .plain)
        tableView?.dataSource = self
        tableView?.delegate = self
        self.view.addSubview(tableView!)

        self.getURLDatas()



    }
    func getURLDatas()
{
        // 此处是极速数据的appKey,若有需要可以去极速数据网站注册并申请
        let appKey = "*************"
        let urlStr = "http://api.jisuapi.com/news/get?channel=头条&start=0&num=10&appkey=\(appKey)"
        print(urlStr)

       let urlString = urlStr.addingPercentEncoding(withAllowedCharacters: CharacterSet(charactersIn: "`#%^{}\"[]|\\<> ").inverted)

        let url = URL.init(string: urlString!)

        let request = URLRequest(url:url!, cachePolicy: .reloadIgnoringCacheData, timeoutInterval: 15.0)

        let session = URLSession.shared

        let task =   session.dataTask(with: request)
        {   (data, response, error) in

            // 解析获取的二进制网络数据
            if error != nil
            {
            print("错误:\(error!)")
            return
            }
            let obj = try! JSONSerialization.jsonObject(with: data!, options: . allowFragments) as! Dictionary

            print(obj)

            let result = obj["result"] as! Dictionary

            let list = result["list"] as! Array

            var newsArr:[News]? = []
            for item in list{
                let newsDic = item as! Dictionary

                let oneNew = News()

                oneNew.title = newsDic["title"] as! String
                oneNew.time = newsDic["time"]  as! String

                oneNew.url = newsDic["url"] as! String

                oneNew.weburl = newsDic["weburl"] as! String


                newsArr?.append(oneNew)


            }
            self.datas = newsArr

            // 回到UI主线程刷新表格
            DispatchQueue.main.async(execute:
                {
            self.tableView?.reloadData()
            })

        }
    task.resume()

}



    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

接下来 我们实现cell的点击进入详情的效果 在创建两个OC文件中,系统会自动生成如图所示的文件:
这里写图片描述
把OC的头文件在这个文件中 再次书写下用以实现与OC的混编
代码如下:

#import "DetailViewController.h"
#import "News.h"

DetailViewController.h 与 .m文件是实现的是新闻的详情
在DetailViewController.h中写一个对外的属性

#import 

@interface DetailViewController : UIViewController

@property(nonatomic,strong)NSString *detailUrl; // 对外详情接口

@end

.m 代码:

#import "DetailViewController.h"

@interface DetailViewController ()

@property(nonatomic,strong)UIWebView *webView;

@end

@implementation DetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    self.webView = [[UIWebView alloc] initWithFrame:self.view.frame];
    [self.view addSubview:self.webView];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    NSString *urlStr = [self.detailUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];




    NSURL *url = [NSURL URLWithString:urlStr];
    NSURLRequest *req = [NSURLRequest requestWithURL:url];

    [self.webView loadRequest:req];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end

在New.h中定义一些要用到的属性

#import 

@interface News : NSObject

@property(nonatomic,strong)NSString *title;
@property(nonatomic,strong)NSString *time;
@property(nonatomic,strong)NSString *url;
@property(nonatomic,strong)NSString *weburl;

@end

想要实现网络数据的展示 还要在pch文件中做一些修改,具体如图:
Swift UI布局+读取网络数据+Swift、OC混编_第2张图片

你可能感兴趣的:(Swift)