简体   繁体   English

Swift:检查customview是否符合协议

[英]Swift: check customview conforms to protocol

I have some custom views, that conforms to a protocol: 我有一些符合协议的自定义视图:

class CustomView1: UIView, MyProtocol {
    ...
}


class CustomView2: UIView, MyProtocol {
    ...
}

Then later, I want to check a view is my custom view or not by check if view conforms to my protocol, but it's not work: 然后,我想通过检查视图是否符合我的协议来检查视图是否是我的自定义视图,但是它不起作用:

let v = view.viewWithTag(1000)

if let _ = v as? MyProtocol {
    print("this is my custom view")
}

if v.self is MyProtocol.Type {
    print("this is my custom view")
}

Any ideas? 有任何想法吗?

Thanks! 谢谢!

Everything fine in code, i think you are getting nil in let v = view.viewWithTag(1000) 代码中的一切都很好,我想您在let v = view.viewWithTag(1000)中获得了零

I have checked your code in playground, it works fine. 我已经在操场上检查了您的代码,效果很好。 在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM