Search code examples
swiftuiimageviewuikit

Custom Capsule Background with UIImageView programmatically not working?


I am returning a single UILabel within a UIImageView, within a Cell for a UICollectionViewController. My didSelectItem and dynamic width or working for the cell.

However I am trying to make the UIImageView a capsule shape, the below code I thought would return a circle but isn't. What I want to make is a capsule background layer for the Text, similar to a button but not a button.

class CategoryView: UIView {
    
    private let capsuleBackground: UIImageView = {
        let view = UIImageView()
        view.layer.backgroundColor = UIColor.white.cgColor
        view.layer.borderWidth = 1
        view.layer.borderColor = COLOR_PRIMARY?.cgColor
        view.layer.cornerRadius = view.frame.size.width/2
        view.translatesAutoresizingMaskIntoConstraints = false
        view.clipsToBounds = true
        view.isUserInteractionEnabled = false
        return view
    }()
    
    private let textLabel: CustomUILabel = {
        let label = CustomUILabel(title: "Hello World")
        return label
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setup()
    }
    
    
    fileprivate func setup() {
        addSubview(capsuleBackground)
        capsuleBackground.addSubview(textLabel)
        
        
        capsuleBackground.centerInSuperview()
        textLabel.edges(to: capsuleBackground, insets: TinyEdgeInsets(top: 8, left: 8, bottom: 8, right: 8))
        
    }
}

this is what it looks like

enter image description here


Solution

  • view.layer.cornerRadius = 12 🤦‍♂️