简体   繁体   English

创建一个类型为 UIView 的变量,该变量符合 swift 中的协议

[英]Create a variable of type UIView that conforms a protocol in swift

Inside a class, I want to add a variable of type UIView, which conforms to the following protocol:在 class 内部,我想添加一个 UIView 类型的变量,它符合以下协议:

public protocol Shadow: UIView {
    func applyShadow()
}

public extension Shadow {
    func applyShadow() {
        self.layer.cornerRadius = 16
        ...
    }
}

To then be able to do something like this:然后能够做这样的事情:

private lazy var shadowView: Shadow = UIView()
shadowView.applyShadow()

I want to do this, so I don't have to bring that function applyShadow() to my class and have repeated code.我想这样做,所以我不必将 function applyShadow()带到我的 class 并重复代码。

Then you need to declare as below然后你需要声明如下

public protocol Shadow {
    func applyShadow()
}

public extension Shadow where Self: UIView {
    func applyShadow() {
        self.layer.cornerRadius = 16
    }
}

Basically, there are 2 ways to do this.基本上,有两种方法可以做到这一点。 One is having a protocol Shadow then creating a concrete class to conform to Shadow protocol as below一个是有一个Shadow协议,然后创建一个具体的 class 以符合Shadow协议,如下所示

public protocol Shadowable where Self: UIView {
    func applyShadow()
}

public class Shadow: UIView, Shadowable {
    func applyShadow() {
        self.layer.cornerRadius = 16
    }
}

Or you can create an extension of UIView in Shadow class或者您可以在Shadow class 中创建 UIView 的扩展

class Shadow: UIView {}

extension UIView {
    func applyShadow() {
        self.layer.cornerRadius = 16
    }
}

The comment box is very limited to the character counts.评论框的字符数非常有限。 so I create another answer所以我创建了另一个答案


public protocol Shadow: UIView {
    func applyShadow()
}

public extension Shadow {
    func applyShadow() {
        self.layer.cornerRadius = 16
    }
}

// re-use Shadow protocol 
//this is a concrete class that conforms to Shadow protocol 
class CardWithTitle: UIView, Shadow {}


class Card: UIView {
   private lazy var oneVariable: CardWithTitle = {
        let view = CardWithTitle()
        view.applyShadow()
        return view
    }()
}

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

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