I want to create a TikTok comments clone, meaning:
- background content should stay in place
- sheet should slide from the bottom
- there should be comment box at the bottom
- tapping on comment box should open a keyboard and the comment box should slide up
Run below code and tap on blue square to active comments. You will see how red background slides to the top
import SwiftUI
struct TikTokView: View {
@State var isPresented: Bool = false
var body: some View {
ZStack {
Color.red
VStack {
RoundedRectangle(cornerRadius: 15)
.fill(Color.blue)
.frame(width: 50, height: 50)
.onTapGesture {
isPresented.toggle()
}
}
.ignoresSafeArea(.keyboard)
CommentsSheetView(isPresented: $isPresented)
}
}
}
struct CommentsSheetView: View {
@Binding var isPresented: Bool
@State private var text: String = ""
var transition: AnyTransition = .move(edge: .bottom)
var body: some View {
ZStack {
if isPresented {
Color.black.opacity(0.5).ignoresSafeArea()
VStack {
Spacer()
ScrollView(.vertical, content: {
VStack {
ForEach(0...50, id: .self) { i in
Text("Comment").foregroundStyle(.pink)
Spacer()
}
}
.frame(maxWidth: .infinity)
})
.frame(height: (550 - 80))
.frame(maxWidth: .infinity)
.padding(.bottom, 80)
.background(.white.opacity(0.1))
}
.ignoresSafeArea(.keyboard)
.fixedSize()
.transition(transition)
VStack {
Spacer()
HStack {
Text("LOREM")
TextField("TESTING", text: $text, axis: .vertical)
.keyboardType(.asciiCapable)
.autocorrectionDisabled(true)
.foregroundStyle(.pink)
}
.frame(minHeight: 50, maxHeight: 100)
.background(.green.opacity(0.1 ))
}
.frame(maxWidth: .infinity)
.transition(transition)
}
}
}
}
#Preview {
TikTokView()
}
2
Answers
I have a working solution, if anyone need it, here's the code:
No need to build this by hand, SwiftUI has build in
Viewmodifier
for this. So what you want can be written like this: