我试图在视图中添加一个边框,并且只在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) )
}
}但是当你中风的时候,这是行不通的。有什么办法可以做到吗?

发布于 2022-11-10 23:40:57
在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)https://stackoverflow.com/questions/74389429
复制相似问题