SwiftUI中的圆角边框

Hex*_*ons 1 swiftui

如何在SwiftUI中修边框?

我认为这会起作用:

.cornerRadius(10)
.border(Color.white)
Run Code Online (Sandbox Code Playgroud)

它不起作用。

这是我目前的解决方法:

.overlay(RoundedRectangle(cornerRadius: 10).stroke(lineWidth: 1).foregroundColor(.white))
Run Code Online (Sandbox Code Playgroud)

tyi*_*ine 8

对于外部对齐的圆形边框,在覆盖之前,您可以在视图中添加一些填充 \xe2\xa4\xb5\xef\xb8\x8e

\n
let strokeWidth: CGFloat = 1\n\nYourView\n    .padding([.all], strokeWidth / 2) // set the width to half of the stroke width\n    .overlay(\n        RoundedRectangle(cornerRadius: 5)\n        .stroke(Color.black, lineWidth: strokeWidth)\n    )\n
Run Code Online (Sandbox Code Playgroud)\n


dfd*_*dfd 6

这不是解决方法,而是在SwiftUI中的操作方式。两件事情:

  • 曾经有一个cornerRadius修饰符在... beta 4中被弃用?Beta 5?是的,这一直是一个移动的目标。

  • 随着巨大的感谢@kontiki(量的博客文章),这里是一个扩展,它很好地返回你想要什么:

    extension View {
        public func addBorder<S>(_ content: S, width: CGFloat = 1, cornerRadius: CGFloat) -> some View where S : ShapeStyle {
            return overlay(RoundedRectangle(cornerRadius: cornerRadius).strokeBorder(content, lineWidth: width))
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)

用法:

.addBorder(Color.white, width: 1, cornerRadius: 10)
Run Code Online (Sandbox Code Playgroud)

  • 这只适用于背景为白色的情况!因为这只是添加一个覆盖层,所以圆角之外的背景颜色仍然可见。 (5认同)

Kir*_*nee 6

寻找圆形和边框的开发人员。

Image("turtlerock")
   .clipShape(Circle())
   .overlay(
       Circle().stroke(Color.white, lineWidth: 4))
Run Code Online (Sandbox Code Playgroud)


osk*_*rko 6

我更喜欢这个:

.background(RoundedRectangle(cornerRadius: 4.0).stroke(borderColor, lineWidth: borderWidth))
.foregroundColor(.blue)
Run Code Online (Sandbox Code Playgroud)

覆盖与偏移方法不兼容......