如何在 Objc 项目中使用 SnapKit?

How could I use SnapKit in Objc project?

我使用 CocoaPods(Xcode 9.3.1 和 Swift 4.1)创建新项目,当然在其中使用 SnapKit。

我想使用第三方 class TreeView,这个 class 由 Objc 编写。

如何在 class TreeView 中使用 SnapKit???

我尝试使用以下步骤但不起作用:

  1. 创建名为 SnapKit-Bridging-Header.h

  2. 的新文件
  3. 进入TreeView.m,导入头文件(注意:以'-Swift'结尾):

    #import "SnapKit-Swift.h"

  4. 编译成功!我可以在 TreeView.m 文件

  5. 中看到 LayoutConstraint(在 SnapKit 中定义)和其他一些 class
  6. 但是当我使用 view.snp.xxx 时,它会抱怨 "Property 'snp' not found ..."

所以我的问题是如何在 ObjC 文件中使用 view.snp.xxx???谢谢:)

Swift 代码无法与 Objective-C 完全互操作。 您只能在 Objective-C 支持的桥接 header 中使用此类 Swift 元素。这个库需要 Swift,它并没有说它支持 Objective-C,所以你可能需要做额外的适配工作来支持它。

在 iOS 9+ 中你有 NSLayoutAnchor API 几乎和 SnapKit 一样容易使用 (参见 https://developer.apple.com/library/content/documentation/UserExperience/Conceptual/AutolayoutPG/ProgrammaticallyCreatingConstraints.htmlhttps://cocoacasts.com/working-with-auto-layout-and-layout-anchors/ ; https://theswiftlibrary.com/the-simple-way-of-creating-constraints-in-code)

此 API 易于使用且与 Objective-C 兼容。

如果你想支持 iOS 8,你可以使用像 this one 这样的向后移植库。