将isKindOfClass与Swift一起使用

 dsjdsjdsjjk_896 发布于 2023-01-11 19:54

我想尝试一下Swift lang,我想知道如何将以下Objective-C转换为Swift:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [super touchesBegan:touches withEvent:event];

    UITouch *touch = [touches anyObject];

    if ([touch.view isKindOfClass: UIPickerView.class]) {
      //your touch was in a uipickerview ... do whatever you have to do
    }
}

更具体地说,我需要知道如何isKindOfClass在新语法中使用.

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {

    ???

    if ??? {
        // your touch was in a uipickerview ...

    }
}

KPM.. 461

正确的Swift运算符是is:

if touch.view is UIPickerView {
    // touch.view is of type UIPickerView
}

当然,如果你还需要将视图分配给一个新的常量,那么if let ... as? ...语法就是你的男孩,正如凯文提到的那样.但是如果您不需要该值并且只需要检查类型,那么您应该使用is运算符.

3 个回答
  • 正确的Swift运算符是is:

    if touch.view is UIPickerView {
        // touch.view is of type UIPickerView
    }
    

    当然,如果你还需要将视图分配给一个新的常量,那么if let ... as? ...语法就是你的男孩,正如凯文提到的那样.但是如果您不需要该值并且只需要检查类型,那么您应该使用is运算符.

    2023-01-11 19:54 回答
  • override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    
        super.touchesBegan(touches, withEvent: event)
        let touch : UITouch = touches.anyObject() as UITouch
    
        if touch.view.isKindOfClass(UIPickerView)
        {
    
        }
    }
    

    编辑

    正如@ Kevin的回答所指出的那样,正确的方法是使用可选的类型转换运算符as?.您可以在section Optional Chaining子节中阅读更多相关信息Downcasting.

    编辑2

    正如用户@KPM的另一个答案所指出的那样,使用is运算符是正确的方法.

    2023-01-11 19:54 回答
  • 您可以将检查和强制转换合并为一个语句:

    let touch = object.anyObject() as UITouch
    if let picker = touch.view as? UIPickerView {
        ...
    }
    

    然后你可以pickerif块内使用.

    2023-01-11 19:55 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有