我已经完成了创建自定义动画按钮的代码安全
import SwiftUI
struct CustomLoginButtons<ButtonText: View>: View { // it can conforms to whatever I want as long it conforms to View protocol
let buttonAction: () -> Void //buttons returns that, just an empty closure
let buttonText: ButtonText // generics for button text whatever i want
@State private var pressed = false // variable that hold states of a button
init(buttonAction: @escaping () -> Void, @ViewBuilder buttonText: () -> ButtonText ) {
//the @escaping it means here that the action will be ignored here, for now, beacause it will be used somewhere else
self.buttonAction = buttonAction
self.buttonText = buttonText()// here its being initialized for building the button text
}
var body: some View {
Button(action: buttonAction) {// here i am passing the action closure to be executed
buttonText
.padding()
.frame(minWidth: 0, maxWidth: .infinity)/* infinity meas that the component will fit the entire view, that way
i can set the size in the view that i want to use this button*/
.background(Capsule().fill(Color.blue))
.foregroundColor(Color.white)
.overlay(RoundedRectangle(cornerRadius: 30).stroke(Color.white, lineWidth: 1.5))
.scaleEffect(self.pressed ? 1.2 : 1.0)
.onLongPressGesture(minimumDuration: .infinity, maximumDistance: .infinity, pressing: { pressing in
let impactHeavy = UIImpactFeedbackGenerator(style: .soft)
impactHeavy.impactOccurred()
withAnimation(.easeInOut(duration: 0.2)) {
self.pressed = pressing
}
}, perform: { })
}
}
}
我目前的问题是当我点击这个按钮时,没有执行操作,我不知道为什么。
CustomLoginButtons(buttonAction: {
print("Tapped")
}) {
Text("Login")
}
我就是这样调用这个按钮的。