ios - Swift:将对象类型转换为其他对象

标签 ios swift

我创建了 UIView 的扩展,以在 UIKeyboard 上为 UITextField/UITextView 添加 UIToolbar。

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。

有什么建议吗?

最佳答案

到 1 textview 不是 textfield
到 2 任何对象都没有方法 inputAccessoryView
-->> swift 强制类型安全

所以你不能只是将对象转换成它们不是的东西

但是

来自文档:
"UIResponder 类为输入 View 和输入附属 View 声明了两个属性:
@property (readonly, retain) UIView *inputView;
@property (readonly, retain) UIView *inputAccessoryView;"

但它在那里是只读的


所以检查类

    var xy:AnyObject!;

    if(xy.isKindOfClass(UITextField)) {
        var t = xy as UITextField;
        //...
    }
    else if(xy.isKindOfClass(UITextView)) {
        var t = xy as UITextView;
        //...
    }

关于ios - Swift:将对象类型转换为其他对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26004677/

相关文章:

ios - 我们使用此 Asyncimageview 类从 Web 服务获取图像并显示在 UItableview 中,但无法正常工作?

swift - 'T' 类型的值没有动态成员 'object' 使用来自根类型 'T' 的 key 路径

ios - 如何检查 Google/Facebook 帐户是否已用于在 Firebase Auth 上创建帐户

ios - 摇动手势不适用于 iOS

ios - Swift 4 重复本地通知

objective-c - 复制 UIImageView 子类

ios - 如何在 iOS 中缩放裁剪叠加图像

ios - Swift 3 尝试呈现其 View 不在窗口层次结构中

ios - 仅在特定场景中显示 adMob 横幅; swift

ios - 在 Xcode 6.1 及更高版本中创建项目时,屏幕在 iOS 7 中缩小