我有三个全局变量:

var activeTextField = UITextField() // stores the last textFieldDidBeginEditing
var activeTextView = UITextView() // stores the last textViewDidBeginEditing
var lastTextKindIsTextView = true // indicates if the last text used is a UITextView

我要计算第一个响应程序文本字段或文本视图的选定字符数。我试过这段代码,但它不起作用,因为activeField超出了范围。有办法吗?
if lastTextKindIsTextView {
    let activeField = activeTextView
} else {
    let activeField = activeTextField
}

// see the length of the selected string
var strLength = 0

// don't work because activeField is out of scope:
if let textRange = activeField.selectedTextRange {
    let selectedText = activeField.text(in: textRange)
    strLength = (selectedText?.utf16.count)!
 }

最佳答案

if - else表达式之前声明变量

let activeField : UITextInput
if lastTextKindIsTextView {
    activeField = activeTextView
} else {
    activeField = activeTextField
}

或不if - else
let activeField : UITextInput = lastTextKindIsTextView ? activeTextView : activeTextField

07-24 17:25