问题描述
在我的应用程序中,我想获得基于相同大小的 SF 符号的简单圆形按钮。但是,相同的方法会根据符号产生不同的图像大小。 例如,带加号的图像大于减号。
为了解决这个问题,我使用了 ZStack 技巧,其中我在减号下放置了一个透明的加号。但我认为这不是最好的解决方案。有没有更好的解决方案?
HStack{
Image(systemName: "plus")
.padding()
.overlay(
Circle()
.stroke(Color.primary,linewidth:1))
Image(systemName: "minus")
.padding()
.overlay(
Circle()
.stroke(Color.primary,linewidth:1))
//my solution
ZStack {
Image(systemName: "plus")
.padding()
.opacity(0.0)
.overlay(
Circle()
.stroke(Color.primary,linewidth:1))
Image(systemName: "minus")
}
}
"minus" in the center has a smaller size than "plus","minus" on the right - my solution
解决方法
您可以使用 ViewModifier 或者如果是按钮 ButtonStyle
视图修饰符
@available(iOS 13.0,*)
struct fillButtonCircle: ViewModifier {
var foregroundColor: Color = .white
var backgroundColor: Color = .green
var dimension: CGFloat = 10
func body(content: Content) -> some View {
content
.foregroundColor(foregroundColor)
.padding(dimension)
.background(backgroundColor)
.clipShape(Circle())
.frame(width: dimension,height: dimension)
.overlay(
Circle()
.stroke(Color.primary,lineWidth:1))
}
}
按钮样式
@available(iOS 13.0,*)
struct CircleScaleButton: ButtonStyle {
var color: Color = .blue
var maxHeight: CGFloat = 35
public func makeBody(configuration: Self.Configuration) -> some View {
configuration.label
.frame(minWidth: 0,maxWidth: .infinity,minHeight: 0,maxHeight: maxHeight,alignment: .center)
.foregroundColor(.black)
.background(RoundedRectangle(cornerRadius: 35/2.0).fill(self.color))
.compositingGroup()
.clipShape(Circle())
.overlay(
Circle()
.stroke(Color.primary,lineWidth:1))
.opacity(configuration.isPressed ? 0.8 : 1.0)
.scaleEffect(configuration.isPressed ? 0.9 : 1.0)
}
}
示例
struct SwiftUIViewTest: View {
var body: some View {
VStack {
Text("Button")
HStack {
Button(action: {},label: {
Image(systemName: "plus")
})
.buttonStyle(CircleScaleButton(color: .clear,maxHeight: 45))
Button(action: {},label: {
Image(systemName: "minus")
})
.buttonStyle(CircleScaleButton(color: .clear,maxHeight: 45))
}
Spacer()
.frame(height: 50)
Text("Image")
HStack {
Image(systemName: "plus")
.modifier(fillButtonCircle(foregroundColor: .black,backgroundColor: .clear,dimension: 40))
Image(systemName: "minus")
.modifier(fillButtonCircle(foregroundColor: .black,dimension: 40))
}
}
}
}
,
使用.circle
import SwiftUI
struct ContentView: View {
var body: some View {
HStack {
Image(systemName: "plus.circle")
.resizable()
.frame(width: 50,height: 50,alignment: .center)
Image(systemName: "minus.circle")
.resizable()
.frame(width: 50,alignment: .center)
}
}
}