ios - 如何在 Objective C 和 swift Viewcontroller 中使用委托(delegate)

标签 ios objective-c swift appdelegate xcode9.2

我的项目结合了一个用 Objective C 编写的 View Controller (objCViewController) 和另一个由 swift 编写的 View Controller (SwiftViewCOntroller)。 我有几个变量 NSString。我想更新 objCViewController 中的字符串,并使用委托(delegate)在 SwiftViewController 中访问它,因为我需要在这两个 View Controller 之间不断更改并不断更新字符串。

这是代码:

objCViewController.h

#import <UIKit/UIKit.h>

@protocol MyDelegate <NSObject>
@end

@interface objCViewController : UIViewController{
  NSString * stringbeingpassed;
}

@property (nonatomic, weak) id<MyDelegate> delegate;
@property (nonatomic, retain) NSString * stringbeingpassed;
@end

objCViewController.m

@implementation objCViewController
@synthesize delegate;
@synthesize stringbeingpassed;

- (void)updatestring {
  //update string in this method
  NSString * newstring = @"testing";

  if (delegate != nil && [delegate respondsToSelector:@selector(stringUpdated:)]) {
    [delegate stringUpdated: newstring];
}

}

桥接 header .h:

#import "objCViewController.h"

SwiftViewController.swift:

protocol MyDelegate {
func stringUpdated(newMessage: String)
}

import UIKit
@objc class SwiftViewController: UIViewController, MyDelegate{
override func viewDidLoad() {
    super.viewDidLoad()
}

func stringUpdated(newMessage:String) {
let newMessage = "sent string"
}

我尝试过使用委托(delegate),但我不知道如何使用它。我对 swift 和 Objective C 完全陌生

Q1。我想问一下如何将我的 newstring 分配给 objCViewController 中的委托(delegate),然后将其传递给 SwiftViewController

第二季度。另一个问题是如何在 SwiftViewController 中检索委托(delegate)中的数据。我应该添加什么?

第三季度。我在定义委托(delegate)时还遗漏了什么吗?我需要在两个 View Controller 中定义它吗? 谢谢。

最佳答案

由于提供的信息很少,很难说代表是否是完成这项工作的正确工具。事实上,我可能建议研究更好的方法来构建您的应用程序。

话虽如此,查看协议(protocol) MyDelegate 的代码会很有帮助。如果这个协议(protocol)还没有,那么它将需要一个接受“String”作为参数的“func”。现在我们将此函数称为stringUpdated。使用提供的代码,您需要将 SwiftViewController 的实例设置为 objCViewController 内的属性delegate。这样,当调用 updatestring 时,您可以执行以下操作:

- (void)updatestring {
    //update string in this method
    NSString * newstring = @"testing";

    if (delegate != nil && [delegate respondsToSelector:@selector(stringUpdated:)]) {
        [delegate stringUpdated: newstring]
    }
}

SwiftViewController中,您必须采用如下协议(protocol):

@objc class SwiftViewController: UIViewController, MyDelegate {

然后通过实现函数stringUpdated来遵守协议(protocol)。

更新

您的协议(protocol)仍然缺少该方法。它应该看起来像这样:

@protocol MyDelegate
- (void) stringUpdated:(NSString *)updatedString;
@end

关于ios - 如何在 Objective C 和 swift Viewcontroller 中使用委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49738052/

相关文章:

ios - Objective-c UIDocumentInteractionController 加载灰屏

objective-c - iOS - CLLocationCoordinate2D/floats/long 到 JSON 的 NSDictionary 中?

ios - 如何在 addTarget 的操作中传递参数?

swift - 如何实现 GameCenter 排行榜?

ios - 缩小图像复制到粘贴板后变得模糊 - Swift 3.0

iphone - UIWebView 和 Richtext 文件

ios - App Review环境中appStoreReceiptURL的路径名是什么?

algorithm - swift中的优先级队列

ios - 使用 MPMoviePlayerController 禁用 AirPlay

iOS被拒绝5次