Swift change backgroundcolor and have rounded corners in an UIVIew?

Viewed 365

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?

3 Answers

Try this solution this may helps you

        droppedView.clipsToBounds = true
        droppedView.layer.cornerRadius = 7
        droppedView.layer.maskedCorners = [.layerMaxXMaxYCorner, .layerMinXMaxYCorner]
        droppedView.backgroundColor = .systemGray6

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)

You could use .clipShape:

droppedView.background(Color.systemGray6)
droppedView.clipShape(Rectangle().roundCorners(corners: [.bottomLeft, .bottomRight], radius: 7))
Related