Round Specific Corners SwiftUI

前端 未结 4 1685
不思量自难忘°
不思量自难忘° 2020-12-02 09:12

I know you can use .cornerRadius() to round all the corners of a swiftUI view but is there a way to round only specific corners such as the top?

4条回答
  •  攒了一身酷
    2020-12-02 09:53

    View Modifiers made it easy:

    struct CornerRadiusStyle: ViewModifier {
        var radius: CGFloat
        var corners: UIRectCorner
    
        struct CornerRadiusShape: 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)
            }
        }
    
        func body(content: Content) -> some View {
            content
                .clipShape(CornerRadiusShape(radius: radius, corners: corners))
        }
    }
    
    extension View {
        func cornerRadius(radius: CGFloat, corners: UIRectCorner) -> some View {
            ModifiedContent(content: self, modifier: CornerRadiusStyle(radius: radius, corners: corners))
        }
    }
    

    Example:

    //left Button
    .cornerRadius(radius: 6, corners: [.topLeft, .bottomLeft])
    
    //right Button
    .cornerRadius(radius: 6, corners: [.topRight, .bottomRight])
    

提交回复
热议问题