我这样制作UIView。但我想在UIViewController中使用它
我该怎么办?

导入UIKit

class CardView: UIView {

    @IBInspectable var cornerRadius: CGFloat = 2

    @IBInspectable var shadowOffsetWidth: Int = 0
    @IBInspectable var shadowOffsetHeight: Int = 3
    @IBInspectable var shadowColor: UIColor? = UIColor.black
    @IBInspectable var shadowOpacity: Float = 0.5

    override func layoutSubviews() {
        layer.cornerRadius = cornerRadius
        let shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius)

        layer.masksToBounds = false
        layer.shadowColor = shadowColor?.cgColor
        layer.shadowOffset = CGSize(width: shadowOffsetWidth, height: shadowOffsetHeight);
        layer.shadowOpacity = shadowOpacity
        layer.shadowPath = shadowPath.cgPath
    }

}

最佳答案

如果要在viewController中添加它,则有几种选择:

  • 将其直接添加到情节提要中(最佳选择):

  • 通过xCode右下方的检查器/对象库在viewController中拖动视图

    UIView object screenshot

    添加约束,然后在

    Constraints screenshot

    并在“身份检查器/自定义类别”字段中选择您的自定义类别
  • 您还可以使用从xib加载的视图
    Google从xib加载的其他方式。
  • 您可以将其添加到代码中。有点难:

  • 创建一个惰性属性:
    lazy var cardView: CardView = {
            let cardView = CardView(frame: CGRect(x: 0, y: 0, width: 100, height: 200))
            cardView.backgroundColor = .gray
            cardView.layer.cornerRadius = 16.0
            return cardView
        }()
    

    例如,在viewDidLoad中添加自定义视图:
    override func viewDidLoad() {
        super.viewDidLoad()
    
        /* Adding subview to the VC */
        view.addSubview(cardView)
    }
    

    然后添加约束。您可以将其垂直/水平居中,然后设置自定义高度/宽度。这取决于你想要...

    看一下这个:
    Swift | Adding constraints programmatically

    我建议您阅读Apple的文档,而不要复制粘贴代码。
    如果您还没有的话,应该绝对阅读“documentation / UserExperience / Conceptual / AutolayoutPG / ProgrammaticallyCreatingConstraints.html”。

    关于ios - 如何在UIViewController iOS中使用UIView,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42758928/

    10-10 20:35
    查看更多