Search code examples
iosobjective-cswiftsnapkit

How could I use SnapKit in Objc project?


I create new project with CocoaPods (Xcode 9.3.1 and Swift 4.1)and of course use SnapKit in it.

and I want use third party class TreeView ,this class wrote by Objc.

How cloud I use SnapKit in class TreeView ???

I try to use the following steps but not working:

  1. create new file named SnapKit-Bridging-Header.h

  2. go to TreeView.m , import the header file (notice:It ends with '-Swift'):

    #import "SnapKit-Swift.h"

  3. compiling now is OK! and I can see LayoutConstraint (defined in SnapKit)and some other class in TreeView.m file

  4. but when I use view.snp.xxx ,it complain "Property 'snp' not found ..."

So my Q is How could I use view.snp.xxx in ObjC file??? Thanks :)


Solution

  • Swift code is not fully interoperable with Objective-C. You can only use such Swift elements in your bridging header that are supported by Objective-C. This library requires Swift, it doesn't say that it supports Objective-C, so it's likely you need to do extra adaptation efforts to support it.

    In iOS 9+ you have NSLayoutAnchor API that is almost as easy to use as SnapKit (see https://developer.apple.com/library/content/documentation/UserExperience/Conceptual/AutolayoutPG/ProgrammaticallyCreatingConstraints.html ; https://cocoacasts.com/working-with-auto-layout-and-layout-anchors/ ; https://theswiftlibrary.com/the-simple-way-of-creating-constraints-in-code)

    This API is easy to use and compatible with Objective-C.

    If you want to support iOS 8, you can use a backporting library like this one.