swiftuikituiimageviewuiimage

Padding around UIImage in a UIImageView with a background color


Basically trying to recreate the small icons like in the iOS Settings app. I have tried numerous techniques from stack over flow and nothing works. I managed to add padding around the UIImage, but the background doesn't fill up together with the padding and just fills right around the uiimage.

let image = UIImage(systemName: "arrow.down")!.withAlignmentRectInsets(UIEdgeInsets(top: -5, left: -5, bottom: -5, right: -5))
        let imageView = UIImageView(image: image)
        imageView.tintColor = .white
        imageView.layer.cornerRadius = 5
        imageView.contentMode = .scaleAspectFit
        imageView.backgroundColor = .systemPink
        imageView.translatesAutoresizingMaskIntoConstraints = false
        addSubview(imageView)

 imageView.widthAnchor.constraint(equalToConstant: 30),
 imageView.heightAnchor.constraint(equalToConstant: 30),

Solution

  • The simple solution is to put the image view in another view. Setup that view with the desired background color and rounded corners.

    let cfg = UIImage.SymbolConfiguration(scale: .medium)
    let image = UIImage(systemName: "arrow.down", withConfiguration: cfg)
    let iv = UIImageView(image: image)
    iv.tintColor = .white
    let icon = UIView(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
    icon.backgroundColor = .systemPink
    icon.layer.cornerRadius = 5
    icon.addSubview(iv)
    addSubview(icon)
    iv.translatesAutoresizingMaskIntoConstraints = false
    icon.translatesAutoresizingMaskIntoConstraints = false
    NSLayoutConstraint.activate([
        iv.centerXAnchor.constraint(equalTo: icon.centerXAnchor),
        iv.centerYAnchor.constraint(equalTo: icon.centerYAnchor),
        icon.widthAnchor.constraint(equalToConstant: 30),
        icon.heightAnchor.constraint(equalToConstant: 30),
        // Add constraints to position icon as needed
    ])