【发布时间】:2021-04-01 07:59:38
【问题描述】:
我已经被这个问题困扰了一段时间,这个主题的类似问题并没有帮助我解决这个问题。
public extension NSString {
func textRectWithFont(font: UIFont, width: CGFloat) -> CGRect {
let contraint: CGSize = CGSize(width: width, height: 500000);
var rect: CGRect
var attributes: [NSAttributedString.Key: Any] = [
.font: font
]
rect = self.boundingRect(with: contraint,
options: [.usesLineFragmentOrigin, .usesFontLeading],
attributes: attributes,
context: nil)
return rect;
}
}
当我在这一行使用那个方法时
let textHeight = NSString(textLabel?.text).textRectWithFont(font: textLabel?.font, width: textFrame?.size.width).size.height
它给了我错误“表达式类型不明确,没有更多上下文”
我做错了什么?
【问题讨论】:
-
因为 textLabel 和 textFrame 是可选的,所以您使用可选参数并且编译器无法将调用与采用非可选参数的函数相匹配。首先尝试使用
if let解包值或允许函数的可选参数并在其中添加错误处理。 -
这是有道理的。谢谢你的解释!