在SwiftUI中更改ProgressView的大小(高度)

26

我在SwiftUI(使用Xcode)中创建了一个ProgressView,并进行了一些编辑,但还没有弄清如何更改其高度。

struct ProgressBar: View {
    var body: some View {
        VStack {
            ProgressView("Progres:", value: 50, total: 100)
        }.foregroundColor(Color(UIColor.systemBlue))
        .scaleEffect(1, anchor: .center)
        .accentColor(Color(UIColor.systemGreen))
    }
}

3
尝试使用.scaleEffect修饰符,就像这里的答案一样。 - aheze
我尝试过那样做,但是它改变了整个ProgressView,而不只是我想要的线性条。 - Michal1
啊,我没有仔细阅读整张图片。 - aheze
请查看以下内容:https://serialcoder.dev/text-tutorials/swiftui/progressview-in-swiftui/ - Hwangho Kim
2个回答

37

我不知道直接改变高度的方法,但是你可以使用.scaleEffect修饰符。请确保在x比例中指定1,以仅增加高度。

struct ContentView: View {
    var body: some View {
        ProgressBar()
        .padding([.leading, .trailing], 10)
    }
}

struct ProgressBar: View {
    var body: some View {
        VStack {
            ProgressView(value: 50, total: 100)
            .accentColor(Color.green)
            .scaleEffect(x: 1, y: 4, anchor: .center)
        }
    }
}

结果: 高度较大的进度条

缺点是您无法传递标签,因为它也会被拉伸。

ProgressView("Progress:", value: 50, total: 100)

垂直拉伸的“进度:”标签

为了解决这个问题,只需在ProgressView上方创建自己的Text即可。

struct ProgressBar: View {
    var body: some View {
        VStack(alignment: .leading) {
            Text("Progress:")
            .foregroundColor(Color.blue)
            
            ProgressView(value: 50, total: 100)
            .accentColor(Color.green)
            .scaleEffect(x: 1, y: 4, anchor: .center)
        }
    }
}

"Progress:" is not stretched


4
可以在ProgressView中创建圆角吗?怎么做? - CGR
3
@CGR 很难定制来自系统的 ProgressView 等组件。自己制作进度条可能更容易。可以参考这个链接:https://www.simpleswiftguide.com/how-to-build-linear-progress-bar-in-swiftui/ - aheze
在我的 macOS Ventura 和 Swift 5.2 上它无法工作。 - Nate Lockwood

15

我需要一个更圆滑的半径,而且不想把ProgressView隐藏在另一个视图中,因此这是我的解决方案(通过使用比例效果扩展 @aheze 的答案)

struct MyProgressViewStyle: ProgressViewStyle {
  var myColor: Color

  func makeBody(configuration: Configuration) -> some View {
      ProgressView(configuration)
          .accentColor(myColor)
          .frame(height: 8.0) // Manipulate height, y scale effect and corner radius to achieve your needed results
          .scaleEffect(x: 1, y: 2, anchor: .center)
          .clipShape(RoundedRectangle(cornerRadius: 6))
          .padding(.horizontal)
  }
}
// Here's how to use it inside a View
ProgressView(value: currentProgress, total: totalProgress)
            .progressViewStyle(MyProgressViewStyle(myColor: Color.green))

1
这是正确的答案。您可以使用ProgressViewStyle自定义ProgressView。被接受的答案是一种技巧。 - Engin Kurutepe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接