我創建了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