SwiftUI - How to add a pageTabView inside a scrollview with PinnedViews - swiftui

I had one problem while using SwiftUI. I have implemented a sectionHeader using PinnedView which is currently scrollable all up and down, has a header area, and is LazyVStack. Below is the implementation to show the corresponding content.
struct ContentView: View {
var body: some View {
ScrollView {
LazyVStack(spacing: 0, pinnedViews: .sectionHeaders) {
Section {
Text("Header")
.frame(maxWidth: .infinity, minHeight: 300)
.background(Color.red)
}
Section {
LazyVStack {
ForEach(0...100, id: \.hashValue) { num in
Text("\(num)")
}
}
} header: {
ZStack {
Color.black.ignoresSafeArea()
Text("Section Header")
.frame(maxWidth: .infinity, minHeight: 50)
.background(Color.black)
}
}
}
}
}
}
https://imgur.com/a/xYIFzgy
However, I did not stop here and declared a TabView to enable horizontal paging scrolling in the corresponding content area as shown below, but nothing was displayed in the Contents area.
struct ContentView: View {
#State private var currentIndex = 0
var body: some View {
ScrollView {
LazyVStack(spacing: 0, pinnedViews: .sectionHeaders) {
Section {
Text("Header")
.frame(maxWidth: .infinity, minHeight: 300)
.background(Color.red)
}
Section {
TabView(selection: $currentIndex) {
LazyVStack {
ForEach(0...100, id: \.hashValue) { num in
Text("A: \(num)")
}
}
.tag(0)
LazyVStack {
ForEach(0...100, id: \.hashValue) { num in
Text("B: \(num)")
}
}
.tag(1)
}
} header: {
ZStack {
Color.black.ignoresSafeArea()
Text("Section Header")
.frame(maxWidth: .infinity, minHeight: 50)
.background(Color.black)
}
}
}
}
}
}
https://imgur.com/a/TvKVoIR
I have found through debugging that if I declare a TabView inside a ScrollView, the Contents area doesn't show anything. Can you give me an idea on how to use the stickyHeader as in the above example to make it horizontally paging?
Thanks

add These Modifiers to the TabView:
TabView {
...
}
.frame(height: UIScreen.main.bounds.height)
.tabViewStyle(.page(indexDisplayMode: .never))

Related

SwiftUI image with borders overlaying button

Thanks to a previous question I asked, I am using Color.black.overlay and .clipped() to show an image with letterbox borders above and below it.
But when I attempt to put a button on the top border, it can't be tapped on (I assume because the image (unclipped) is in that space, and is intercepting the tap gesture).
Here is what the layout looks like:
Here is the code:
var body: some View {
ZStack {
Color.black
VStack {
topBorder
imageMiddle
bottomBorder
}
}
.ignoresSafeArea()
}
var topBorder: some View {
return Group {
ZStack {
Rectangle()
.fill(.green)
.frame(minHeight: borderHeight, maxHeight: borderHeight)
Button {
print("tap")
} label: {
Image(systemName: "hand.tap.fill")
.foregroundColor(.black)
}
}
}
}
var bottomBorder: some View {
return Group {
Rectangle()
.fill(.green)
.frame(minHeight: borderHeight, maxHeight: borderHeight)
}
}
var imageMiddle: some View {
return Group {
Color.black.overlay(
Image("cat")
.scaledToFill()
)
.clipped()
}
}
How can I expose that button to a user's tap?
Adding .allowsHitTesting(false) to your image view will fix it. However, it seems like the wrong approach.
VStack {
topBorder
imageMiddle
.allowsHitTesting(false) // <- This will fix your problem.
bottomBorder
}
I would recommend using another approach to add your borders on top of the image instead. Something like this:
ZStack {
imageMiddle
VStack {
topBorder
.overlay(alignment: .bottom) {
Rectangle().frame(minHeight: 0, maxHeight: 10)
}
Spacer()
bottomBorder
.overlay(alignment: .top) {
Rectangle().frame(minHeight: 0, maxHeight: 10)
}
}
}
.ignoresSafeArea()

Show BottomPlayerView above TabView in SwiftUI

I'm learning swiftUI and I want to make a music app.
I created a view which going to be above the tabView, but I want it to be shown only if user start playing a music.
My App, I use ZStack for bottomPlayer, and I share the bottomPlayer variable through .environmentObject(bottomPlayer) so the child views can use it:
class BottomPlayer: ObservableObject {
var show: Bool = false
}
#main
struct MyCurrentApp: App {
var bottomPlayer: BottomPlayer = BottomPlayer()
var audioPlayer = AudioPlayer()
var body: some Scene {
WindowGroup {
ZStack(alignment: Alignment(horizontal: .center, vertical: .bottom)) {
TabBar()
if bottomPlayer.show {
BottomPlayerView()
.offset(y: -40)
}
}
.environmentObject(bottomPlayer)
}
}
}
The BottomPlayerView (above the TabView)
struct BottomPlayerView: View {
var body: some View {
HStack {
Image("cover")
.resizable()
.frame(width: 50, height: 50)
VStack(alignment: .leading) {
Text("Artist")
.foregroundColor(.orange)
Text("Song title")
.fontWeight(.bold)
}
Spacer()
Button {
print("button")
} label: {
Image(systemName: "play")
}
.frame(width: 60, height: 60)
}
.frame(maxWidth: .infinity, maxHeight: 60)
.background(Color.white)
.onTapGesture {
print("ontap")
}
}
}
My TabView:
struct TabBar: View {
var body: some View {
TabView {
AudiosTabBarView()
VideosTabBarView()
SearchTabBarView()
}
}
}
And In my SongsView, I use the EnvironmentObject to switch on the bottomPlayerView
struct SongsView: View {
#EnvironmentObject var bottomPlayer: BottomPlayer
var body: some View {
NavigationView {
VStack {
Button {
bottomPlayer.show = true
} label: {
Text("Show Player")
}
}
.listStyle(.plain)
.navigationBarTitle("Audios")
}
}
}
The problem is the bottomPlayer.show is actually set to true, but doesn't appear ...
Where I am wrong?
In your BottomPlayer add theĀ #Published attribute before the show boolean.
This creates a publisher of this type.
apple documentation

Scrollable content not working as expected in SwiftUI

I'm trying to create a scroll view with my custom view, but when I add scroll to view it's not working as expected, without scroll view working fine.
struct ContentView: View {
var body: some View {
ScrollView(.vertical) {
VStack {
ForEach (0..<2) { _ in
ListItem()
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
// But the below code is working fine.
struct ContentView: View {
var body: some View {
VStack {
ForEach (0..<2) { _ in
ListItem()
}
}
}
}
// List Item
struct ListItem: View {
var body: some View {
VStack {
HStack {
Image("steve")
.resizable()
.clipShape(Circle())
.aspectRatio(contentMode: .fit)
.frame(maxWidth:44, maxHeight: 44)
VStack {
Text("Steve Jobs")
.font(.headline)
.frame(maxWidth: .infinity, alignment: .leading)
Text("1 hour ago")
.font(.footnote)
.frame(maxWidth: .infinity, alignment: .leading)
}
Spacer()
}
ZStack(alignment:.top) {
GeometryReader { geometry in
VStack {
ZStack {
Image("poster_1")
.resizable()
.aspectRatio(contentMode: .fit)
.cornerRadius(8)
.shadow(color: Color.black.opacity(0.12),
radius: 4, x: 1, y: 1)
.frame(width: geometry.size.width - 64,
height: geometry.size.height * 0.35)
.padding([.horizontal], 32)
.clipped()
ZStack {
Rectangle()
.fill(Color.black.opacity(0.75))
.frame(maxWidth:84 , maxHeight: 84)
.cornerRadius(12)
Image(systemName: "play.fill")
.font(.system(size: 44, weight: .bold))
.foregroundColor(.white)
}
}
VStack {
Text("Game of Thrones")
.accentColor(Color.gray.opacity(0.25))
.font(Font.subheadline.weight(.bold))
.padding([.horizontal], 32)
.padding([.bottom], 2)
.frame(maxWidth: .infinity,
alignment: .leading)
VStack {
Text("Game of Thrones is an American fantasy drama television series created by David Benioff and D. B. Weiss for HBO. ")
.accentColor(Color.gray.opacity(0.25))
.font(.footnote)
.frame(maxWidth: .infinity,
alignment: .leading)
.padding([.horizontal], 32)
Text("Show more...")
.accentColor(Color.gray.opacity(0.01))
.font(Font.footnote.weight(.bold))
.frame(maxWidth: .infinity,
alignment: .trailing)
.padding([.trailing], 32).onTapGesture {
print("okay")
}
}
}
}
}
}
}
}
}
ListItem contains multiple views which creates publisher info and movie information as shown below image.
Scrollview is scrolling but images are not shown in view as first image.
It is the geometry reader that you have in ListItem. Because neither a GeometryReader nor a Scrollview have their own size. Since neither no what size to render, they collapse. This is what you are seeing in your view. See this answer. The solution is to put the GeometryReader into ContentView outside the Scrollview and send the GeometryProxy that you called geometry into ListItem something like this:
struct ContentView: View {
var body: some View {
GeometryReader { geometry in
ScrollView(.vertical) {
VStack {
ForEach (0..<2) { _ in
ListItem(geometry: geometry)
}
}
} // Scrollview
} // GeometryReader
}
}
struct ListItem: View {
let geometry: GeometryProxy
var body: some View {
...
}
This seems to fix it in Preview, though you may have to change your multipliers in the .frame() that uses geometry to size it how you want.

SwiftUI not centering when in ZStack

I am trying to put together a view that consists of a top header view, a bottom content view, and a view that sits on top centered on the line splitting the two views. I figured out I need an alignment guide within a ZStack to position the middle view but I am having problems getting the items in the lower content view centered without a gap.
This code:
extension VerticalAlignment {
struct ButtonMid: AlignmentID {
static func defaultValue(in context: ViewDimensions) -> CGFloat {
return context[.bottom]
}
}
static let buttonMid = VerticalAlignment(ButtonMid.self)
}
struct ContentView: View {
var body: some View {
VStack {
ZStack(alignment: Alignment(horizontal: .center, vertical: .buttonMid)) {
HeaderView()
.frame(maxWidth: .infinity, minHeight: 200, idealHeight: 200, maxHeight: 200, alignment: .topLeading)
// BodyView()
// .alignmentGuide(.buttonMid, computeValue: { dimension in
// return dimension[VerticalAlignment.top]
// })
Color.red
.frame(width: 380, height: 50, alignment: /*#START_MENU_TOKEN#*/.center/*#END_MENU_TOKEN#*/)
.alignmentGuide(.buttonMid, computeValue: { dimension in
return dimension[VerticalAlignment.center]
})
}
BodyView()
}
.edgesIgnoringSafeArea(.top)
}
}
struct HeaderView: View {
var body: some View {
Color.green
}
}
struct BodyView: View {
var body: some View {
VStack {
Spacer()
HStack {
Spacer()
BodyContent()
Spacer()
}
Spacer()
}
.background(Color.blue)
}
}
struct BodyContent: View {
var body: some View {
VStack {
Text("Line 1")
Text("Line 2")
Text("Line 3")
}
}
}
give you this:
which centers the lower content they way I want it however it leaves a gap between the upper and lower views. If I uncomment the BodyView code in the ZStack and comment it out in the VStack like so:
struct ContentView: View {
var body: some View {
VStack {
ZStack(alignment: Alignment(horizontal: .center, vertical: .buttonMid)) {
HeaderView()
.frame(maxWidth: .infinity, minHeight: 200, idealHeight: 200, maxHeight: 200, alignment: .topLeading)
BodyView()
.alignmentGuide(.buttonMid, computeValue: { dimension in
return dimension[VerticalAlignment.top]
})
Color.red
.frame(width: 380, height: 50, alignment: /*#START_MENU_TOKEN#*/.center/*#END_MENU_TOKEN#*/)
.alignmentGuide(.buttonMid, computeValue: { dimension in
return dimension[VerticalAlignment.center]
})
}
// BodyView()
}
.edgesIgnoringSafeArea(.top)
}
}
gives you:
which leaves the content uncentered. How can I keep it centered? I tried putting it in a GeometryReader and that had the same results.
You don't need a custom VerticalAlignment. Instead you can put the middle view as an overlay and align it to the top border of the bottom view:
struct ContentView: View {
var body: some View {
VStack(spacing: 0) {
HeaderView()
.frame(height: 200)
BodyView()
.overlay(
Color.red
.frame(width: 380, height: 50)
.alignmentGuide(.top) { $0[VerticalAlignment.center] },
alignment: .top
)
}
.edgesIgnoringSafeArea(.top)
}
}

SwiftUI Tabbar persists navigationBarTitle position in tab's views

How can I stop a tab's scrollview's offset being affect by other tab's offset?
I don't want to force the scroll view to the top every time you show a new tab, but just want the new tabs to be not affected by the scroll position of the last tab I viewed.
import SwiftUI
enum Tab {
case First, Second, Third
var title: String {
switch self {
case .First:
return "First"
case .Second:
return "Second"
case .Third:
return "Third"
}
}
}
struct ContentView: View {
#State var selectedTab = Tab.First
var body: some View {
NavigationView {
TabView(selection: $selectedTab) {
FirstView()
.tabItem {
Text("First")
}.tag(Tab.First)
SecondView()
.tabItem {
Text("Second")
}.tag(Tab.Second)
ThirdView()
.tabItem {
Text("Third")
}.tag(Tab.Third)
}.navigationBarTitle(selectedTab.title, displayMode: .automatic)
.navigationBarHidden(false)
}
}
}
struct FirstView: View {
let data = [1,2,3,4,5,6,7,8,9,10]
var body: some View {
ScrollView(showsIndicators: true) {
VStack {
ForEach(data, id: \.self) { item in
Text("\(item)")
.frame(minWidth: 0, idealWidth: 100, maxWidth: .infinity, minHeight: 0, idealHeight: 100, maxHeight: .infinity, alignment: .center)
}
}
}
}
}
struct SecondView: View {
let data = [1,2,3,4,5,6,7,8,9,10]
var body: some View {
ScrollView(showsIndicators: true) {
VStack {
ForEach(data, id: \.self) { item in
Text("\(item)")
.frame(minWidth: 0, idealWidth: 100, maxWidth: .infinity, minHeight: 0, idealHeight: 100, maxHeight: .infinity, alignment: .center)
}
}
}
}
}
struct ThirdView: View {
let data = [1,2,3,4,5,6,7,8,9,10]
var body: some View {
ScrollView(showsIndicators: true) {
VStack {
ForEach(data, id: \.self) { item in
Text("\(item)")
.frame(minWidth: 0, idealWidth: 100, maxWidth: .infinity, minHeight: 0, idealHeight: 100, maxHeight: .infinity, alignment: .center)
}
}
}
}
}
It is because you use one NavigationView, so it preserves own state. Make NavigationView independent for each tab.
Tested with Xcode 12 / iOS 14
struct ContentView: View {
#State var selectedTab = Tab.First
var body: some View {
TabView(selection: $selectedTab) {
NavigationView {
FirstView()
.navigationBarTitle(Tab.First.title)
}
.tabItem {
Text("First")
}.tag(Tab.First)
NavigationView {
SecondView()
.navigationBarTitle(Tab.Second.title)
}
.tabItem {
Text("Second")
}.tag(Tab.Second)
NavigationView {
ThirdView()
.navigationBarTitle(Tab.Third.title)
}
.tabItem {
Text("Third")
}.tag(Tab.Third)
}
}
}