gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 10:07:41 26 4
gpt4 key购买 nike

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

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/

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