我创建了UIView的扩展,在UIKeyboard上为UITextField/UITextView添加UIToolbar。Swift:将对象转换为其他对象
extension UIView {
public func addDoneOnKeyboardWithTarget (target : AnyObject, action : Selector) {
//Creating UIToolbar
var toolbar = UIToolbar()
//Configuring toolbar
var items = NSMutableArray()
var nilButton = IQBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
items.addObject(nilButton)
var doneButton = IQBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: target, action: doneAction)
items.addObject(doneButton)
toolbar.items = items
//Now typecasting self to UITextField for compilation purposes because `inputAccessoryView` is readonly for UIView. it's readwrite for UITextField and UITextView both.
var textField : UITextField = self as UITextField //Runtime error for UITextView
//Setting new toolbar as inputAccessoryView
textField.inputAccessoryView = toolbar
}
}
它适用于UITextField,但是当我在UITextView上调用上述函数时,它在类型转换时崩溃。
尝试1: 我试过将其转换为可选
var textField : UITextField? = self as? UITextField
textField?.inputAccessoryView = toolbar
现在,它不会对UITextView的崩溃,但也没有设置任何inputAccessoryView。当我试图打印它。它在控制台上打印nil
。
println(textField?.inputAccessoryView) //It prints 'nil'
尝试2: 我想它转换为AnyObject
var textField : AnyObject = self as AnyObject
textField.inputAccessoryView = toolbar //Compile time error
如果我更换的UITextField到那么明显的UITextView它工作正常进行的UITextView但不适合的UITextField。
有什么建议吗?
一个TextView没有文本框和任何对象有没有方法inputAccessoryView - SWIFT强制类型安全 – 2014-09-23 21:13:56
是的,我知道,但我应该如何克服上述问题。我将我的开源库转换为swift https://github.com/hackiftekhar/IQKeyboardManager/blob/master/IQKeyBoardManager/IQUIView%2BIQKeyboardToolbar.m见175行 – 2014-09-23 21:17:57