iOS開發之OC與swift開發混編教程,代理的相互調用,block的實現。OC調用Swift中的代理, OC調用Swift中的Block 閉包

来源:https://www.cnblogs.com/jukaiit/archive/2018/11/06/8927050.html
-Advertisement-
Play Games

本文章將從兩個方向分別介紹 OC 與 swift 混編 1. 第一個方向從 swift工程 中引入 oc類 1. 1 如何在swift的類中使用oc類 1.2 如何在swift中實現oc的代理方法 1.3 如何在swift中實現oc的Block回調 2 二個方向從OC工程中引入swift類 2.1 ...


 

本文章將從兩個方向分別介紹 OC 與 swift 混編  

1. 第一個方向從 swift工程 中引入 oc類 

  1. 1 如何在swift的類中使用oc類
    1.2  如何在swift中實現oc的代理方法
    1.3   如何在swift中實現oc的Block回調

2 二個方向從OC工程中引入swift類

 

    2.1  如何在OC類中使用swift類
    2.2   如何在OC中實現swift的代理方法
    2.3   如何在OC中實現swift中類似Block回調

 

 

下麵是具體的實現過程:

 1.1  如何在swift的類中使用oc類? 

1.  swift工程中引入OC類。 具體實現過程。

    1.1 新建一個swift工程類。 取名 swiftOrOC

    1.2  實現的功能為 :  從swift. viewController.swift 中 push到 OC語言 secondViewController 控制器

1.2.1  新建SecondViewController 類 。

        

     1.2.2 建立橋接文件。 (很重要)

 

    一定要記得點擊這個按鈕。 

       1.2.3  接下來工程目錄如下:

       

     1.2.4 接下來就可以實現具體的跳轉功能了。 

      ViewController.swift中具體實現

     

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var hintLabel: UILabel!  //稍後用來顯示回調
    
    // push 到 oc controller
    @IBAction func pushAction(_ sender: AnyObject) {
        let secondVC = SecondViewController.init()
        self.navigationController?.pushViewController(secondVC, animated: true)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

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

 

 

1.2 如何在swift中實現oc的代理方法

       1.2.1 首先在 SecondViewController.h 中聲明一個協議。具體代碼

        

#import <UIKit/UIKit.h>

@protocol SecondDelegate <NSObject>

-(void)refreshHintLabel:(NSString *)hintString;

@end

@interface SecondViewController : UIViewController

@property (nonatomic,weak)id<SecondDelegate> secondDelegate;
@end

 

 

  1.2.3 接下來就非常簡單了,讓ViewController.swift只需要成為SecondViewController的代理,然後遵循她的協議,就可以了。 具體代碼如下。

 

       1.2.3.1 遵循協議

  

     1.2.3.2 成為代理,並實現協議方法,更改controller.swift中hintLabel的text。

[objc] view plain copy  
  1. // push 到 oc controller  
  2. @IBAction func pushAction(_ sender: AnyObject) {  
  3.     let secondVC = SecondViewController.init()  
  4.     secondVC.secondDelegate = self;  
  5.     self.navigationController?.pushViewController(secondVC, animated: true)  
  6. }  
  7.   
  8. // SecondViewControll的代理方法  
  9. func refreshHintLabel(_ hintString: String!) {  
  10.     hintLabel.text = "secondView textView.text = " + hintString;  
  11. }  

 

 

 

 1.3   如何在swift中實現oc的Block回調

1.3.1 具體過程與1.2小節一樣。 直接上代碼。

 

        1.3.2 聲明block;

         

[objc] view plain copy  
  1. typedef void(^RefreshHintLabelBlock)(NSString *hintString);  
  2.   
  3. @interface SecondViewController : UIViewController  
  4. @property (nonatomic, copy) RefreshHintLabelBlock hintBlock;  
  5. @end  

 

 

        1.3.3 block的回調。 SecondViewController.m中

 

[objc] view plain copy  
  1. #pragma mark 返回上一頁回調 ,將用戶輸入的用戶名傳回給 ViewController.swift  
  2. -(BOOL)navigationShouldPopOnBackButton{      
  3.     if (_hintBlock) {  
  4.         _hintBlock(textField.text);  
  5.     }  
  6.     return YES;  
  7. }  

 

 

        1.3.4 在swift類中調用 oc的block.

 

[objc] view plain copy  
  1. // push 到 oc controller  
  2. @IBAction func pushAction(_ sender: AnyObject) {  
  3.     let secondVC = SecondViewController.init()  
  4.       secondVC.secondDelegate = self;  
  5.     secondVC.hintBlock = {(t:String?)in  
  6.         self.hintLabel.text = "secondView textView.text = " + t!  
  7.     }  
  8.     self.navigationController?.pushViewController(secondVC, animated: true)  
  9. }  



 

   工程已上傳到git上,git地址: https://github.com/zhonggaorong/SwiftOrOc/tree/master

2.  OC工程中引入swift類。 具體實現過程。

    耽誤了不少時間, 今天才開始寫oc工程中引入swift類。

    demo地址: 

  

 

     2.1  如何在OC類中使用swift類

         2.1.1   新建一個基於OC語言的工程 ,取名 OcOrSwiftTwo        2.1. 2  實現的功能為 : 從oc類 viewcontroller中, push 至 swift語言 SecondViewController  ,然後SecondViewController可以通過代理或者swift閉包把值傳回viewcontroller.         2.1.3   當前文件目錄看下圖:  (第四個箭頭: 橋接文件)         

       2.2   如何在OC中實現swift的代理與閉包Block方法                  2.2.1 如何在oc中引入swift類。#import "工程名-swift.h" [objc] view plain copy  
  1. #import "OcOrSwiftTwo-swift.h"  
   2.2.2 在secondViewController.swift 中實現代理與閉包,代碼如下:     註意: @objc(代理名)  才能在外部可見這個代理   [objc] view plain copy  
  1. import UIKit  
  2. import Foundation  
  3.   
  4. // 必須加上@objc 代理才能在oc類中可見。  
  5. @objc(EditTextFieldDelegate)  
  6. protocol EditTextFieldDelegate:NSObjectProtocol {  
  7.     func editTextField(_ str: String) -> Void  
  8. }  
  9.   
  10. @objc(SecondViewController)  
  11. class SecondViewController: UIViewController {  
  12.   
  13.     var editorDelegate:EditTextFieldDelegate?  
  14.     var textField:UITextField?  
  15.     var addButton:UIButton?  
  16.     var pushButton:UIButton?  
  17.       
  18.     typealias editorBlock = (_ t:String) -> Void  
  19.     var myEidtorBlock:editorBlock?  
  20.       
  21.     override func viewDidLoad() {  
  22.         super.viewDidLoad()  
  23.         self.view.backgroundColor = UIColor.white  
  24.         textField = UITextField.init(frame: CGRect.init(x: 50, y: 60, width: 200, height: 50))  
  25.         textField?.placeholder = "輸入返迴首頁的內容"  
  26.         self.view.addSubview(textField!)  
  27.           
  28.         addButton = UIButton.init(type: .custom)  
  29.         addButton?.setTitleColor(UIColor.black, for: .normal)  
  30.         addButton?.setTitle("pop", for: .normal)  
  31.         addButton?.frame = CGRect.init(x: 50, y: 150, width: 200, height: 50)  
  32.         addButton?.layer.borderColor = UIColor.black.cgColor  
  33.         addButton?.layer.borderWidth = 1.0  
  34.         addButton?.addTarget(self, action: #selector(popAction), for: .touchUpInside)  
  35.         self.view.addSubview(addButton!)  
  36.           
  37.           
  38.           
  39.         pushButton = UIButton.init(type: .custom)  
  40.         pushButton?.setTitleColor(UIColor.black, for: .normal)  
  41.         pushButton?.setTitle("push", for: .normal)  
  42.         pushButton?.frame = CGRect.init(x: 50, y: 250, width: 200, height: 50)  
  43.         pushButton?.layer.borderColor = UIColor.black.cgColor  
  44.         pushButton?.layer.borderWidth = 1.0  
  45.         pushButton?.addTarget(self, action: #selector(pushAction), for: .touchUpInside)  
  46.         self.view.addSubview(pushButton!)  
  47.           
  48.     }  
  49.       
  50.     func popAction() -> Void {  
  51.           
  52.         if editorDelegate != nil {  
  53.             editorDelegate?.editTextField((textField?.text)!)  
  54.         }  
  55.           
  56.         if ((self.myEidtorBlock) != nil){  
  57.             self.myEidtorBlock!((textField?.text!)!)  
  58.         }  
  59.           
  60.         self.navigationController?.popViewController(animated: true)  
  61.     }  
  62.       
  63.       
  64.     func pushAction() -> Void {  
  65.         let three = ThreeViewController.init()  
  66.         self.navigationController?.pushViewController(three, animated: true)  
  67.           
  68.     }       
    2.2.3   在oc類中viewcontroller.m 文件中實現SecondviewController.swift的相關代理與閉包(block). 代碼如下:     [objc] view plain copy  
  1. #import "ViewController.h"  
  2. #import "OcOrSwiftTwo-swift.h"  
  3.   
  4. @interface ViewController ()<EditTextFieldDelegate>  
  5. @property (nonatomic, strong) UITextField *showTextField;  
  6. @property (nonatomic, strong) UIButton *pushButton;  
  7.   
  8. @end  
  9.   
  10. @implementation ViewController  
  11.   
  12. - (void)viewDidLoad {  
  13.     [super viewDidLoad];  
  14.     _showTextField = [[UITextField alloc]initWithFrame:CGRectMake(50, 100 , 200, 50)];  
  15.     _showTextField.placeholder = @"swift傳回的文本內容";  
  16.     _showTextField.adjustsFontSizeToFitWidth = YES;  
  17.     _showTextField.enabled = NO;  
  18.     [self.view addSubview:_showTextField];  
  19.       
  20.     _pushButton = [UIButton buttonWithType:UIButtonTypeCustom];  
  21.     [_pushButton.layer setBorderColor:[UIColor blackColor].CGColor];  
  22.     [_pushButton.layer setBorderWidth:1.0];  
  23.     [_pushButton setFrame:CGRectMake(50, 200, 200, 50)];  
  24.     [_pushButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];  
  25.     [_pushButton setTitle:@"push" forState:UIControlStateNormal];  
  26.     [_pushButton addTarget:self action:@selector(pushAction) forControlEvents:UIControlEventTouchUpInside];  
  27.       
  28.     [self.view addSubview:_pushButton];  
  29. }  
  30.   
  31.   
  32.   
  33.   
  34. -(void)pushAction{  
  35.     SecondViewController *second = [[SecondViewController alloc]init];  
  36.     // second.editorDelegate = self;  
  37.       
  38.     /* 
  39.       swift中的閉包回滴 
  40.      */  
  41.     second.myEidtorBlock = ^(NSString *str) {  
  42.         _showTextField.text = [NSString stringWithFormat:@"second傳回信息: %@",str];  
  43.     };  
  44.     [self.navigationController pushViewController:second animated:YES];  
  45. }  
  46.   
  47. #pragma mark swift中的代理  
  48. -(void)editTextField:(NSString *)str{  
  49.     _showTextField.text = [NSString stringWithFormat:@"second傳回信息: %@",str];  
  50. }  
  51.   
  52. - (void)didReceiveMemoryWarning {  
  53.     [super didReceiveMemoryWarning];  
  54.     // Dispose of any resources that can be recreated.  
  55. }  

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 作者:天山老妖S 鏈接:http://blog.51cto.com/9291927 一、存儲過程簡介 1、存儲過程簡介 存儲過程是一組具有特定功能的SQl語句集組成的可編程的函數,經編譯創建並保存在資料庫中,用戶可通過指定存儲過程的名字並給定參數來調用執行。 存儲過程是資料庫管理中常用的技術之一,可 ...
  • 事務定義 事務是單個的工作單元。事務是在資料庫上按照一定的邏輯順序執行的任務序列,既可以由用戶手動執行,也可以由某種資料庫程式自動執行。 事務分類 自動提交事務 每條單獨的語句都是一個事務。 顯式事務 每個事務均以 BEGIN TRANSACTION 語句顯式開始,以 COMMIT 或 ROLLBA ...
  • 如果我們用成語來形容近幾年的大數據產業,也許最合適的就是:如火如荼! 從大量融資、大數據從業者薪資上漲、從研發到商業應用的技術,到2017年的大數據產業可以說已經贏得了全世界的關註。然而,當涉及到大數據時,很多人認為普通人根本無法進去。真的是這樣嗎?普通人只看招聘人員的巨額薪水嗎? 事實上,只要找到 ...
  • 歡迎大家前往 "騰訊雲+社區" ,獲取更多騰訊海量技術實踐乾貨哦~ 本文由 "騰訊雲資料庫 TencentDB" 發表於 "雲+社區專欄" 鄒鵬 ,騰訊高級工程師,騰訊雲資料庫Redis負責人,多年資料庫、網路安全研發經驗。在網路、計算、存儲、安全等領域有深入的研究和豐富的產品化經驗。 在Redis ...
  • 本文系列文章: ​ 使用Shell 操作 MongoDB的技巧 ​ MongoTemplate的使用技巧及其註意事項 敬請期待。 前言 最近公司想要做一個用戶行為數據的收集,最開始想用mysql來存儲後來發現這種方式對於不固定數據格式的保存存在局限性,也不利於查詢統計操作。所以衍生了使用mongod ...
  • Oracle視圖詳解 一. 視圖的定義 視圖(view),也稱虛表, 不占用物理空間,這個也是相對概念,因為視圖本身的定義語句還是要存儲在數據字典里的。視圖只有邏輯定義。每次使用的時候,只是重新執行SQL。 視圖是從一個或多個實際表中獲得的,這些表的數據存放在資料庫中。那些用於產生視圖的表叫做該視圖 ...
  • LevelDb有如下一些特點: 首先,LevelDb是一個持久化存儲的KV系統,和Redis這種記憶體型的KV系統不同,LevelDb不會像Redis一樣狂吃記憶體,而是將大部分數據存儲到磁碟上。 其次,LevleDb在存儲數據時,是根據記錄的key值有序存儲的,就是說相鄰的key值在存儲文件中是依次順 ...
  • 引言 join是SQL中的常用操作,良好的表結構能夠將數據分散到不同的表中,使其符合某種規範(mysql三大範式),可以最大程度的減少數據冗餘,更新容錯等,而建立表和表之間關係的最佳方式就是join操作。 對於Spark來說有3種Join的實現,每種Join對應的不同的應用場景(SparkSQL自動 ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...