【问题标题】:Round specific border corner with SwiftUI使用 SwiftUI 圆特定边框角
【发布时间】:2022-11-11 07:40:57
【问题描述】:

我正在尝试向视图添加边框并仅围绕 topLeading 和 topTrailing 角。似乎很难实现?使用此扩展程序很容易绕过角落:

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)
    }
}

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

但这在您应用中风时不起作用。任何想法如何实现这一目标?

【问题讨论】:

    标签: swiftui


    【解决方案1】:

    在 SwiftUI 中为视图添加边框的常用方法是通过 .overlay() 修饰符。使用您已经制作的RoundedCorner 形状,我们可以修改this answer 以创建一个新的修饰符,该修饰符将圆形形状添加边框。

    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)
        }
    }
    
    extension View {
        public func borderRadius<S>(_ content: S, width: CGFloat = 1, cornerRadius: CGFloat, corners: UIRectCorner) -> some View where S : ShapeStyle {
            let roundedRect = RoundedCorner(radius: cornerRadius, corners: [.topLeft, .topRight])
            return clipShape(roundedRect)
                .overlay(roundedRect.stroke(content, lineWidth: width))
        }
    }
    

    用法:

    Color.yellow
    .borderRadius(Color.red, width: 15, cornerRadius: 25, corners: [.topLeft, .topRight])
    .padding()
    .frame(width: 300, height: 150)
    

    【讨论】:

      猜你喜欢
      • 2021-06-11
      • 1970-01-01
      • 2019-11-07
      • 2023-01-10
      • 1970-01-01
      • 1970-01-01
      • 2010-09-24
      • 2023-01-17
      • 1970-01-01
      相关资源
      最近更新 更多