我正在尝试将以下代码翻译成Swift 3.我觉得其他海报已经回答了这个问题,但我似乎无法解决这个问题。
- (BOOL)allowTouchForSubview:(UIView *)subview {
NSArray *classes = @[[UITextField class], [UISearchBar class], [UITextView class]];
for (Class class in classes) {
if ([subview isKindOfClass:class]) {
return YES;
}
if ([subview.superview isKindOfClass:class]) {
return YES;
}
};
return NO;
}
这是我到目前为止所拥有的:
func allowTouchForSubview(subview: UIView) -> Bool {
let allowedClasses: [AnyClass] = [UITextField.self, UISearchBar.self, UITextView.self]
for classType in allowedClasses {
if subview is classType {
return true
}
if let superview = subview.superview {
if superview is classType {
return true
}
}
}
return false
}
对classType
的两个引用都有错误,并说明使用了未声明的类型classType'。这是怎么回事?
答案 0 :(得分:2)
试试这个:
func allowTouchForSubview(subview: UIView) -> Bool {
let allowedClasses: [AnyClass] = [UITextField.self, UISearchBar.self, UITextView.self]
for classType in allowedClasses {
if subview.isKind(of: classType) || (subview.superview?.isKind(of: classType) ?? false) {
return true
}
}
return false
}
进行测试:
let test = UITextView()
allowTouchForSubview(subview: test)//prints true
let textField = UITextField()
allowTouchForSubview(subview: textField)//prints true
let subview = UIView()
allowTouchForSubview(subview: subview) //prints false
test.addSubview(subview)
allowTouchForSubview(subview: subview) //prints true