Last active
January 25, 2021 15:00
-
-
Save megabitsenmzq/5357ad8c8633e6a7b927242e125238d1 to your computer and use it in GitHub Desktop.
A simple alert view in SwiftUI.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
struct PopoutAlertView: View { | |
let lightTapticGenerator = UIImpactFeedbackGenerator(style:.light) | |
@State private var isHidden = true | |
var title = "Alert" | |
var content = "Content here" | |
var tintColor = UIColor.red | |
var onTapButtonCancel: (() -> Void)? | |
let onTapButtonOk: () -> Void | |
var body: some View { | |
ZStack { | |
RoundedRectangle(cornerRadius: 15, style: .continuous) | |
.shadow(color: Color.black.opacity(0.2), radius: 10) | |
.foregroundColor(Color(UIColor.systemBackground)) | |
.layoutPriority(-1) | |
VStack(spacing: 0){ | |
Group{ | |
Text(title) | |
.font(.headline) | |
.padding(.top, 5) | |
Text(content) | |
.font(.body) | |
.lineLimit(nil) | |
.fixedSize(horizontal: false, vertical: true) | |
} | |
.padding() | |
.padding(.leading, 10) | |
.padding(.trailing, 10) | |
.foregroundColor(Color.black) | |
HStack { | |
if onTapButtonCancel != nil { | |
Button(action: { | |
withAnimation(.linear(duration: 0.2)) { | |
self.isHidden = true | |
} | |
lightTapticGenerator.impactOccurred() | |
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2, execute: { | |
self.onTapButtonCancel?() | |
}) | |
}, label: { | |
RoundedRectangle(cornerRadius: 10, style: .continuous) | |
.foregroundColor(.gray) | |
.frame(height: 40) | |
.overlay( | |
Text("Cancel").foregroundColor(.white) | |
) | |
}) | |
} | |
Button(action: { | |
withAnimation(.linear(duration: 0.2)) { | |
self.isHidden = true | |
} | |
lightTapticGenerator.impactOccurred() | |
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2, execute: { | |
self.onTapButtonOk() | |
}) | |
}, label: { | |
RoundedRectangle(cornerRadius: 10, style: .continuous) | |
.foregroundColor(Color(tintColor)) | |
.frame(height: 40) | |
.overlay( | |
Text("OK").foregroundColor(.white) | |
) | |
}) | |
}.padding() | |
} | |
} | |
.frame(minWidth: 300, maxWidth: 400) | |
.padding(50) | |
.opacity(isHidden ? 0 : 1) | |
.scaleEffect(isHidden ? 0.95 : 1) | |
.onAppear(perform: { | |
withAnimation(.linear(duration: 0.2)) { | |
self.isHidden = false | |
} | |
}) | |
} | |
} | |
struct PopoutAlertView_Previews: PreviewProvider { | |
static var previews: some View { | |
PopoutAlertView(onTapButtonCancel: { | |
}, onTapButtonOk: { | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment