gpt4 book ai didi

ios - 调用字符串扩展,包括从 Objective-C 中用 Swift 编写的函数

转载 作者:行者123 更新时间:2023-11-28 05:36:43 25 4
gpt4 key购买 nike

当 Swift 中的扩展仅使用如下变量时:

 extension NSString   {
var isNumber: Bool {
return length > 0 && rangeOfCharacter(from: CharacterSet.decimalDigits.inverted).location == NSNotFound
}
}

我可以使用非常友好的语法从 Objective-C 调用它:

NSString *str = @"twelve";
BOOL isNumber = str.isNumber;

但是,当扩展使用如下函数时,我在语法上苦苦挣扎:

extension String {
func asImage(withAttributes attributes: [NSAttributedString.Key: Any]? = nil, size: CGSize? = nil) -> UIImage? {
let size = size ?? (self as NSString).size(attributes: attributes as! [String : Any])
if #available(iOS 10.0, *) {
return UIGraphicsImageRenderer(size: size).image { _ in
(self as NSString).draw(in: CGRect(origin: .zero, size: size),
withAttributes: attributes as! [String : Any])
}
} else {
// Fallback on earlier versions
return nil
}
}

这可以从 Swift 调用,只需:

 var image = "Hello World".asImage()

但我不知道如何从 Objective-C 中调用它。

事实上,autotype 甚至无法识别 str.asImage,当我尝试各种操作时,它会把我引向一个充满错误的兔子洞并修复它,从而导致其他错误。

如何从 Objective-C 调用上述扩展?

最佳答案

Swift 类、扩展或协议(protocol)只有在可转换或显式标记为 @objc 时才能在 Objective-C 中表示。这意味着它需要所有参数都可以转换为 Objective-C

struct 也不能被转换,所以只剩下类(IE:类和具体类的扩展)并且标记一个类 @objc,它必须继承 NSObject.

例子:

@objc
extension NSString {
func asImage(withAttributes attributes: [NSAttributedString.Key: Any]? = nil, size: CGSize = .zero) -> UIImage? {
let size = size == .zero ? self.size(withAttributes: attributes!) : size
if #available(iOS 10.0, *) {
return UIGraphicsImageRenderer(size: size).image { _ in
self.draw(in: CGRect(origin: .zero, size: size),
withAttributes: attributes!)
}
} else {
// Fallback on earlier versions
return nil
}
}
}

请注意,我将 CGSize 参数更改为非可选参数,并改为与零进行比较。

另请注意,我将其标记为@objc 并将其更改为对NSString 的扩展,因为String 本身无法转换为Objective-C因为它是一个结构!

然后在 Objective-C 中你可以这样调用它:

[str asImageWithAttributes:@{....} size:CGSizeZero];

或者你想要的任何参数..

关于ios - 调用字符串扩展,包括从 Objective-C 中用 Swift 编写的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58423761/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com