How to change width of Divider in SwiftUI?

半世苍凉 提交于 2021-01-02 06:53:28

问题


On few screens of my SwiftUI app I am using Divider() between few elements. This Divider is rendered as a very thin grey (or black?) line. I am guessing 1 point. How can I change the width of Divider()?


回答1:


You can create any divider you wish, colors, width, content... As in below example.

struct ExDivider: View {
    let color: Color = .gray
    let width: CGFloat = 2
    var body: some View {
        Rectangle()
            .fill(color)
            .frame(height: width)
            .edgesIgnoringSafeArea(.horizontal)
    }
}



回答2:


For anyone interested, I modified accepted answer with support for both horizontal and vertical directions, as well as used original Divider colors with support for Dark Mode:

struct ExtendedDivider: View {
    var width: CGFloat = 2
    var direction: Axis.Set = .horizontal
    @Environment(\.colorScheme) var colorScheme
    var body: some View {
        ZStack {
            Rectangle()
                .fill(colorScheme == .dark ? Color(red: 0.278, green: 0.278, blue: 0.290) : Color(red: 0.706, green: 0.706, blue: 0.714))
                .applyIf(direction == .vertical) {
                    $0.frame(width: width)
                    .edgesIgnoringSafeArea(.vertical)
                } else: {
                    $0.frame(height: width)
                    .edgesIgnoringSafeArea(.horizontal)
                }
        }
    }
}

Bonus, this snippet uses applyIf syntax:

extension View {
    @ViewBuilder func applyIf<T: View>(_ condition: @autoclosure () -> Bool, apply: (Self) -> T, else: (Self) -> T) -> some View {
        if condition() {
            apply(self)
        } else {
            `else`(self)
        }
    }
}


来源:https://stackoverflow.com/questions/58787180/how-to-change-width-of-divider-in-swiftui

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!