1

I make UIView like this. but I want to use this in UIViewController What should I do?

import 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
    }

}
AMAN77
  • 6,218
  • 9
  • 45
  • 60
candy
  • 11
  • 2

2 Answers2

1

If you want to add it in your viewController you have several options:

  1. Add it directly in storyboard (best option):

drag a view in viewController via inspector/object library on the bottom right side in xCode

UIView object screenshot

add constraints, then tap on the view in

Constraints screenshot

and pick your custom class in identity inspector/custom class field

  1. You can also use a view loaded from xib Google different way to load from xib.

  2. You can add it in code. It's a little bit harder:

Create a lazy property:

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
    }()

Add custom view in viewDidLoad for example:

override func viewDidLoad() {
    super.viewDidLoad()

    /* Adding subview to the VC */
    view.addSubview(cardView)
}

Then add constraints. You can center it vertically/horizontally and then set custom height/width. It depends on what you want...

Check this out: Swift | Adding constraints programmatically

I advise you to read Apple's documentation rather then just copy pasting code. Should definitely read "documentation/UserExperience/Conceptual/AutolayoutPG/ProgrammaticallyCreatingConstraints.html" if you still haven't.

Community
  • 1
  • 1
Oleh Zayats
  • 2,423
  • 1
  • 16
  • 26
0

Add a new uiview to your storyboard or xib file and set its class as CardView as shown enter image description here

abdullahselek
  • 7,893
  • 3
  • 50
  • 40