问题描述
我是一名新的iOS开发人员.我想知道如何在Swift中生成条形码.
I am a new iOS developer. I was wondering how can I generate a barcode in Swift.
我已经有了代码,可以从多种资源中学习如何读取条形码,但是没有找到任何有关从字符串生成条形码的信息.
I have the code already, there are multiple resources from where to learn how to read a barcode, but I didn't find any that talks about generating one from a string.
非常感谢!
P.S.我知道对此也有类似的问题,但这是针对Objective-C的.我不了解Obj-C,但发现来自.NET很难.
P.S. I know there is a similar question about this, but it's for Objective-C. I don't know Obj-C and I find it difficult coming from .NET.
推荐答案
您可以使用CoreImage(import CoreImage
)过滤器来做到这一点!
You could use a CoreImage (import CoreImage
) filter to do that!
具有guard
和失败的初始化程序的新版本:
A newer version, with guard
and failable initialiser:
extension UIImage {
convenience init?(barcode: String) {
let data = barcode.data(using: .ascii)
guard let filter = CIFilter(name: "CICode128BarcodeGenerator") else {
return nil
}
filter.setValue(data, forKey: "inputMessage")
guard let ciImage = filter.outputImage else {
return nil
}
self.init(ciImage: ciImage)
}
}
用法:
let barcode = UIImage(barcode: "some text") // yields UIImage?
根据文档:
这篇关于如何在Swift中从字符串生成条形码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!