在textview中获取lineHeight的nil错误

时间:2015-08-26 11:17:41

标签: ios swift

我正在使用以下代码创建textview。但我得到了

fatal error: unexpectedly found nil while unwrapping an Optional value

错误。

我的代码:

var textField : UITextView!
textField = UITextView(frame: CGRect(x: 0, y: self.view.bounds.height/2 - 50, width: self.view.bounds.width, height: 36))
self.view.addSubview(textField)
textField.editable=true
var amountOfLinesToBeShown:CGFloat = 6
var maxHeight:CGFloat = textField.font.lineHeight * amountOfLinesToBeShown
textField.sizeThatFits(CGSizeMake(textField.frame.size.width, maxHeight))

我收到textField.font.lineHeight

的错误

我该如何解决?

3 个答案:

答案 0 :(得分:0)

为您修正了选项和CGFloats:

var textField : UITextView?
textField = UITextView(frame: CGRect(x: CGFloat(0), y: self.view.bounds.height/2 - 50, width: self.view.bounds.width, height: CGFloat(36)))
self.view.addSubview(textField!)
textField!.editable=true
var amountOfLinesToBeShown = CGFloat(6)
var maxHeight = CGFloat(textField!.font.lineHeight * amountOfLinesToBeShown)
textField!.sizeThatFits(CGSizeMake(textField!.frame.size.width, maxHeight))

答案 1 :(得分:0)

来自文档:

  

var font:UIFont! //默认为nil。使用系统字体12 pt

所以你需要这样做:

if let currentFont = textField.font {
    let maxHeight:CGFloat = currentFont.lineHeight * amountOfLinesToBeShown
    textField.sizeThatFits(CGSizeMake(textField.frame.size.width, maxHeight))
}

如果可能,您应该使用let代替var,所以:

let textField : UITextView?

let amountOfLinesToBeShown = CGFloat(6)

let maxHeight:CGFloat

答案 2 :(得分:0)

memo的字体属性是可选的。你需要打开它。在您的示例中,它将如下所示:

UITextView