Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift change backgroundcolor and have rounded corners in an UIVIew?

I have a problem changing the backgroundcolor and making rounded corners the same time.

droppedView.roundCorners(corners: .bottomLeft, radius: 7)
droppedView.roundCorners(corners: .bottomRight, radius: 7)
droppedView.backgroundColor = .systemGray6

When I do it like this, my View has rounded corners, but there is no backgroundcolor.

Is there a solution to this problem?

like image 854
Fabian Stiewe Avatar asked Sep 15 '25 08:09

Fabian Stiewe


2 Answers

Try this solution this may helps you

        droppedView.clipsToBounds = true
        droppedView.layer.cornerRadius = 7
        droppedView.layer.maskedCorners = [.layerMaxXMaxYCorner, .layerMinXMaxYCorner]
        droppedView.backgroundColor = .systemGray6
like image 159
Muhammad Nawaz Avatar answered Sep 17 '25 04:09

Muhammad Nawaz


UIKit

You could use layer.cornerRadius in UIKit:

    droppedView.clipsToBounds = true
    droppedView.layer.cornerRadius = 7

    droppedView.layer.maskedCorners = [.layerMaxXMaxYCorner, .layerMinXMaxYCorner]
    droppedView.backgroundColor = .systemGray6

SwiftUI

clip.Shape is available in SwiftUI.

First, create File View+Extensions.swift:

import SwiftUI

extension View {
    func cornerRadius(_ radius: CGFloat, corners: UIRectCorner) -> some View {
        clipShape( RoundedCorner(radius: radius, corners: corners))
    }
}

struct RoundedCorner: Shape {

    var radius: CGFloat = .infinity
    var corners: UIRectCorner = .allCorners

    func path(in rect: CGRect) -> Path {
        let path = UIBezierPath(roundedRect: rect, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
        return Path(path.cgPath)
    }
}

and then, go to View.Swift:

Rectangle().cornerRadius(50, corners: .bottomRight)
Rectangle().cornerRadius(50, corners: .bottomLeft)
like image 39
bdeviOS Avatar answered Sep 17 '25 04:09

bdeviOS