Swift UI Demo- 表格,标签,文本框,按钮,网络请求Oc混编

Swift UI Demo- 表格,标签,文本框,按钮,网络请求Oc混编_第1张图片
注意:数据请求要在info.plist文件里加上App Transport Security Settings并设置Allow Arbitrary Loads为YES

AppDelegate.swift

import UIKit
import CoreData

@UIApplicationMain
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:StudentViewController = StudentViewController()
        stuVc.navigationItem.title = "学生名单"
        stuVc.view.backgroundColor = UIColor.white
        let stuNav:UINavigationController = UINavigationController.init(rootViewController: stuVc)

        let uiVc:MyUIViewController = MyUIViewController()
        uiVc.navigationItem.title = "控件视图"
        uiVc.view.backgroundColor = UIColor.white
        let uiNav = UINavigationController(rootViewController: uiVc)

        let newsVc = NewsViewController()
        newsVc.navigationItem.title = "新闻头条"
        newsVc.view.backgroundColor = UIColor.brown
        let newsNav = UINavigationController(rootViewController: newsVc)

        stuNav.tabBarItem = UITabBarItem.init(title: "学生", image: UIImage.init(named: "hospital"), 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
    }

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
        // Saves changes in the application's managed object context before the application terminates.
        self.saveContext()
    }

    // MARK: - Core Data stack

    lazy var persistentContainer: NSPersistentContainer = {
        /*
         The persistent container for the application. This implementation
         creates and returns a container, having loaded the store for the
         application to it. This property is optional since there are legitimate
         error conditions that could cause the creation of the store to fail.
        */
        let container = NSPersistentContainer(name: "SwiftUIDemo")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

                /*
                 Typical reasons for an error here include:
                 * The parent directory does not exist, cannot be created, or disallows writing.
                 * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                 * The device is out of space.
                 * The store could not be migrated to the current model version.
                 Check the error message to determine what the actual problem was.
                 */
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        return container
    }()

    // MARK: - Core Data Saving support

    func saveContext () {
        let context = persistentContainer.viewContext
        if context.hasChanges {
            do {
                try context.save()
            } catch {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                let nserror = error as NSError
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
            }
        }
    }

}

StudentViewController.swift表格类

import UIKit

class StudentViewController: 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)


        // Do any additional setup after loading the view.
    }

    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 Lable,TextField,Button类

import UIKit

class MyUIViewController: UIViewController,UITextFieldDelegate {

    var myLable:UILabel = UILabel.init(frame:CGRect(x: 20, y: 60, width: 100, height: 30))
    var myBtn:UIButton?
    var myTextField:UITextField?

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        myLable.textColor  = UIColor.red
        myLable.textAlignment = .center
        myLable.backgroundColor = UIColor.gray
        myLable.text = "北京"
        myLable.font = UIFont.systemFont(ofSize: 16)
        self.view.addSubview(myLable)

        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!)

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

    }

    func btnPress(sender:UIButton) -> Void {
        sender.isSelected = !sender.isSelected
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

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

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        //获取目前textfield控件中的文本内容
        let text = textField.text

        let newText = (text! as NSString).replacingCharacters(in: NSMakeRange(range.location, range.length), with: string)

        return newText.characters.count <= 8
    }
    /*
    // 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 网络请求Oc 混编

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 indentifier = "cell"
        var cell = tableView.dequeueReusableCell(withIdentifier: indentifier)
        if cell == nil {
            cell = UITableViewCell.init(style: .subtitle, reuseIdentifier: indentifier)
        }
        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 viewDidLoad() {
        super.viewDidLoad()
        tableView = UITableView.init(frame: self.view.frame, style: .plain)
        tableView?.dataSource = self
        tableView?.delegate = self
        self.view.addSubview(tableView!)
        self.getURLDatas()
        // Do any additional setup after loading the view.
    }


    func getURLDatas(){
        let appKey = "de394933e1a3e2db"

        let urlStr = "http://api.jisuapi.com/news/get?channel=头条&start=0&num=10&appkey=\(appKey)"

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

        let request = URLRequest(url: url!, cachePolicy:.reloadIgnoringLocalCacheData, 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

            //回到主线程刷新表格
            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.
    }
    */

}

DetailViewController.h Oc控制器

#import 

@interface DetailViewController : UIViewController
@property (nonatomic,strong)NSString *detailUrl; //对外接口
@end

DetailViewController.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

News.h Oc Model 类

#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

SwiftUIDemo-Bridging-Header.h 混编头文件

//
//  Use this file to import your target's public headers that you would like to expose to Swift.
//

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

你可能感兴趣的:(swift)