从Swift应用程序调用Objective-C方法 [英] Call an Objective-C Method from Swift app
本文介绍了从Swift应用程序调用Objective-C方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在完全使用Swift制作Mac应用程序.现在,我需要向该应用程序添加一个Objective-C函数,但是我不知道该怎么做.我对Objective-C的了解很少,但是我需要将此pdf制作功能添加到我的应用中:
I am making a Mac app, entirely in Swift. Now, I need to add an Objective-C function to the app, but I can't figure out how. I have very little knowledge about Objective-C, but I need to add this pdf-making function to my app:
void MyCreatePDFFile (CGRect pageRect, const char *filename)// 1
{
CGContextRef pdfContext;
CFStringRef path;
CFURLRef url;
CFDataRef boxData = NULL;
CFMutableDictionaryRef myDictionary = NULL;
CFMutableDictionaryRef pageDictionary = NULL;
path = CFStringCreateWithCString (NULL, filename, // 2
kCFStringEncodingUTF8);
url = CFURLCreateWithFileSystemPath (NULL, path, // 3
kCFURLPOSIXPathStyle, 0);
CFRelease (path);
myDictionary = CFDictionaryCreateMutable(NULL, 0,
&kCFTypeDictionaryKeyCallBacks,
&kCFTypeDictionaryValueCallBacks); // 4
CFDictionarySetValue(myDictionary, kCGPDFContextTitle, CFSTR("My PDF File"));
CFDictionarySetValue(myDictionary, kCGPDFContextCreator, CFSTR("My Name"));
pdfContext = CGPDFContextCreateWithURL (url, &pageRect, myDictionary); // 5
CFRelease(myDictionary);
CFRelease(url);
pageDictionary = CFDictionaryCreateMutable(NULL, 0,
&kCFTypeDictionaryKeyCallBacks,
&kCFTypeDictionaryValueCallBacks); // 6
boxData = CFDataCreate(NULL,(const UInt8 *)&pageRect, sizeof (CGRect));
CFDictionarySetValue(pageDictionary, kCGPDFContextMediaBox, boxData);
CGPDFContextBeginPage (pdfContext, pageDictionary); // 7
myDrawContent (pdfContext);// 8
CGPDFContextEndPage (pdfContext);// 9
CGContextRelease (pdfContext);// 10
CFRelease(pageDictionary); // 11
CFRelease(boxData);
}
(该代码来自 如何将代码桥接到Swift,以及如何从Swift视图控制器中调用它?
编辑:我正在使用Swift 3和Xcode 8 beta 5.
I'm using Swift 3 and Xcode 8 beta 5.
推荐答案
以下是iOS应用的解决方案:
Here's the solution for an iOS app:
文件 Thing.h :
#import <UIKit/UIKit.h>
@interface Thing : NSObject
void MyCreatePDFFile (CGRect pageRect, const char *filename);
@end
文件 Thing.m :
#import "Thing.h"
@implementation Thing
void MyCreatePDFFile (CGRect pageRect, const char *filename) {
// ... your code here ...
}
@end
在桥接标题中:
#import "Thing.h"
现在,您的Swift代码可以看到并调用此函数了.
Now your Swift code can see and call this function.
这篇关于从Swift应用程序调用Objective-C方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文