ios - 使用未解析的标识符 'boundingRect'

标签 ios swift ios-extensions

我在使用以下代码时遇到了非常奇怪的问题。

extension String {
        func height(withConstrainedWidth width: CGFloat, font: UIFont) -> CGFloat {
            let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
            let boundingBox = boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSAttributedStringKey.font: font], context: nil)

            return ceil(boundingBox.height)
        }
}

它总是抛出以下编译器错误。

enter image description here

但是如果我使用 self.boundingRect 然后它编译成功并运行应用程序但是在模拟器上启动应用程序后它会自动恢复到再次 boundingRect (删除 self ).

所以每次我需要添加self. 来执行app.

最佳答案

因为boundingRectNSStringextension方法

extension NSString {

    @available(iOS 7.0, *)
    open func draw(with rect: CGRect, options: NSStringDrawingOptions = [], attributes: [NSAttributedStringKey : Any]? = nil, context: NSStringDrawingContext?)

    @available(iOS 7.0, *)
    open func boundingRect(with size: CGSize, options: NSStringDrawingOptions = [], attributes: [NSAttributedStringKey : Any]? = nil, context: NSStringDrawingContext?) -> CGRect
}

因此,如果您将 String 更改为 NSString extension,它将起作用

extension NSString {
    func height(withConstrainedWidth width: CGFloat, font: UIFont) -> CGFloat {
        let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
        
        let boundingBox = boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSAttributedStringKey.font: font], context: nil)
        
        return ceil(boundingBox.height)
    }
}

来自 Swift 团队的编辑

https://bugs.swift.org/browse/SR-8408

The code in the compiler that says "NSString's members show up on String values" is specifically looking for member syntax, i.e. "foo.bar"—or in this case, "self.bar". It probably shouldn't have been written that way, but it was.

I think we'd still recommend being explicit here, even if it's ugly: (self as NSString).boundingRect(…) or let nsSelf = self as NSString; nsSelf.boundingRect(…).

关于ios - 使用未解析的标识符 'boundingRect',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51590399/

相关文章:

每两个请求之一中出现 Swift Alamofire "The request timed out"

swift - 多部分图像 Alamofire 4 swift 3

ios - 检查 iOS 框架项目中的 "Allow app extension API only"将内部类和方法暴露给消费者

ios - 我可以在一个容器应用程序上创建两个自定义键盘吗

ios - 如何在 UISplitViewController 中命名后退按钮

ios - Bitbucket iOS管道yml文件设置

swift - 我需要在其路径中使用编码的前言斜杠快速创建一个 URL(没有层次意义)

ios - 如何添加Today Widget Chevron

ios - 根据检索到的数据类型创建自定义单元格

ios - iTunes Store Search API 中的空结果