gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 05:59:27 26 4
gpt4 key购买 nike

我创建了 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com