简体   繁体   中英

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)

I have checked your code in playground, it works fine. 在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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