Skip to content

Instantly share code, notes, and snippets.

@NewFieldForMe
Created August 3, 2020 10:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NewFieldForMe/c5cb8a5a83a3113dd3b9ee16bb5dbc76 to your computer and use it in GitHub Desktop.
Save NewFieldForMe/c5cb8a5a83a3113dd3b9ee16bb5dbc76 to your computer and use it in GitHub Desktop.
import SwiftUI
import Combine
class KeyboardService: ObservableObject {
@Published var keyboardHeight: CGFloat = 0.0
let defaultNotification = NotificationCenter.default
func start() {
defaultNotification.addObserver(
self,
selector: #selector(self.keyboardWillShow(_:)),
name: UIResponder.keyboardWillShowNotification,
object: nil)
defaultNotification.addObserver(
self,
selector: #selector(self.keyboardWillHide(_:)),
name: UIResponder.keyboardWillHideNotification,
object: nil)
}
func end() {
NotificationCenter
.default
.removeObserver(
self,
name: UIResponder.keyboardWillShowNotification,
object: nil)
NotificationCenter
.default
.removeObserver(
self,
name: UIResponder.keyboardWillHideNotification,
object: nil)
}
@objc func keyboardWillShow(_ notification: Notification) {
guard let rect = (notification
.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { return }
self.keyboardHeight = rect.size.height
}
@objc func keyboardWillHide(_ notification: Notification) {
self.keyboardHeight = 0
}
}
struct ContentView: View {
var body: some View {
InputView()
}
}
struct InputView: View {
@State var inputText = ""
@State var outputText = ""
@ObservedObject var keyboard = KeyboardService()
var body: some View {
ZStack {
VStack {
Text(outputText)
TextField(
"入力してね",
text: $inputText,
onEditingChanged: { editing in
}).padding()
}
FloatingButton(
bottomPadding: self.keyboard.keyboardHeight,
tappedHandler: self.showText,
isDisabled: inputText.isEmpty
)
}.onAppear {
self.keyboard.start()
}.onDisappear {
self.keyboard.end()
}
}
func showText() {
outputText = inputText
}
}
struct FloatingButton: View {
var bottomPadding: CGFloat = 0
var tappedHandler: (() -> Void)? = nil
var isDisabled: Bool = false
var body: some View {
VStack {
Spacer()
HStack {
Spacer()
Button(action: {
self.tappedHandler?()
}, label: {
Image(systemName: "pencil")
.foregroundColor(.white)
.font(.system(size: 24))
})
.frame(width: 60, height: 60)
.background(backgroundColor)
.cornerRadius(30.0)
.shadow(color: .gray, radius: 3, x: 3, y: 3)
.padding(EdgeInsets(top: 0, leading: 0, bottom: bottomPadding + 16.0, trailing: 16.0))
.animation(.easeOut)
.disabled(isDisabled)
}
}
}
var backgroundColor: Color {
return isDisabled ? Color.gray : Color.orange
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment