从 Obj C didSelectionRow 调用 Swift ViewController

Call Swift ViewController from Obj C didSelectionRow

我有一个 Obj C 项目,我在其中添加了 Swift viewController。

我正在尝试将故事板附加到 viewController。

我可以通过编程方式向视图中添加内容,但我无法显示故事板。

我也曾尝试使用 xib 作为 Swift viewController 的竞争,但没有成功。

从 didSelectRowAtInexPath 调用 Swift 表单 Obj C:

SwiftController *sc = [[SwiftController alloc] init];
[self.navigationController pushViewController:sc animated:YES];

SwiftController.swift:

import Foundation
import UIKit

@objc class SwiftController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()

        // This prints
        println("in the scrolling view")
        // This works
        self.view.backgroundColor = .redColor();
    }

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

故事板已正确连接:

这就是我每次得到的:

xib 也有同样的结果。

Apple Docs 和网络上以及 SO 上有很多东西可以处理很多问题 "around" 这个但是我没有找到任何可以帮助我了解我在做什么的东西这里错了。按照可行的方式做事或 Obj C 似乎行不通。 显然我是 Swift 的菜鸟。任何帮助都会很棒。谢谢。

因为在这种情况下,您要初始化一个新的 SwiftController 而不是使用故事板中的那个。您将想要对新故事板 vc 执行 segue 或从

获取 vc
self.storyboard.instantiateViewControllerWithIdentifier(_controller id_)

使用故事板有两种基本方法:

  1. 当您有 Objective-C 代码需要转换到故事板中的另一个场景时,您可以:

    • 在 Interface Builder 中为目标场景指定故事板 ID(例如 SwiftControllerScene);

    • 使用故事板instantiateViewControllerWithIdentifier实例化目标视图控制器;和

    • 过渡到新场景(即推送或呈现该视图控制器)。

    因此:

    SwiftController *sc = [self.storyboard instantiateViewControllerWithIdentifier:@"SwiftControllerScene"];
    [self.navigationController pushViewController:sc animated:YES];
    
  2. 或者,当使用故事板时,与其手动实例化目标的视图控制器然后调用 pushViewController,我更愿意在视图控制器之间的故事板中设置一个 segue (参见 )。然后我会以编程方式执行 segue(当然,引用你给 segue 的任何故事板标识符):

    [self performSegueWithIdentifier:@"SegueToSwiftScene" sender:self];
    

    这样,情节提要板继续代表应用程序的视觉流程。

请注意,目标场景的视图控制器是用 Swift 与 Objective-C 编写的这一事实在很大程度上并不重要。问题仅仅是源视图控制器使用什么语言(因此上面的例子在 Objective-C 中)并且无论目标视图控制器的语言如何,该过程在其他方面基本相同。

如果您为 swift viewController 使用 xib,您必须像这样初始化它:

SwiftController* controller = [[SwiftController alloc]  initWithNibName:@"SwiftController" bundle:nil]

其中 SwiftController 也是您的 xib 的名称。

我在 iOS 8 中注意到这个问题,但它在 iOS 9 和 iOS 10 中正常工作,当您像这样初始化控制器时:

SwiftController* controller = [[SwiftController alloc]  init];