TabView tabItem image move to top - swiftui

I learned how to create a tabBar like UIKit tabBar in swiftUI. And I want to move the center tabItem to top . Is there any way I can achieve this?
TabView code
TabView {
ViewTasks()
.tabItem {
Image(systemName: "list.bullet.below.rectangle")
Text("View Tasks")
}
AddTask()
.tabItem {
Image(systemName: "plus.circle").font(.system(size: 60))
}
CategoriesTasks()
.tabItem {
Image(systemName: "square.grid.2x2")
Text("Categories")
}
}
Visual Example

First idea is to use ZStack so you can cover tabItem with your own tappable image. Here is example:
struct TabViewModel: View {
#State var showActionSheet: Bool = false
var body: some View {
ZStack {
GeometryReader { geometry in
TabView {
Text("list")
.tabItem {
Image(systemName: "list.bullet.below.rectangle")
}
Text("plus")
.tabItem {
Text(" ")
}
Text("categories")
.tabItem {
Image(systemName: "square.grid.2x2")
}
}
Image(systemName: "plus.circle")
.resizable()
.frame(width: 40, height: 40)
.shadow(color: .gray, radius: 2, x: 0, y: 5)
.offset(x: geometry.size.width / 2 - 20, y: geometry.size.height - 80)
.onTapGesture {
self.showActionSheet.toggle()
}
}
}
.actionSheet(isPresented: $showActionSheet) {
ActionSheet(title: Text("some actions"))
}
}
}
so some image will cover center tabView item, which will be invisible (Text(" ")):
update
if you still need to switch between these 3 views you can use #State var selection (don't forget to tag(...) tabItems):
struct TabViewModel: View {
#State var selection: Int = 0
var body: some View {
ZStack {
GeometryReader { geometry in
TabView(selection: self.$selection) {
//...
Text("plus")
.tabItem {
Text(" ")
}.tag(1)
//...
.onTapGesture {
self.selection = 1
}
// ...
}

SWIFTUI 2
.onTapGesture usage sometimes causes unexpected behavior such as not displaying the overlay view (alert, sheets or fullscreen) or displaying it when you click another tab. The safer way is to set the selection value with the .onChange(of:) method:
struct TabViewModel: View {
#State var selection: Int = 0
var body: some View {
ZStack {
GeometryReader { geometry in
TabView(selection: self.$selection) {
//...
Text("plus")
.tabItem {
Text(" ")
}.tag(1)
//...
.onChange(of: selection) { _ in
self.selection = 1
}
// ...
}

Related

SwiftUI: Double picker wheels with system behavioral

I want to recreate system picker behavioral with two options in wheels with SwiftUI and faced ton of problem. Some of this I solved but some still unsolved. I have pop-ups with different views inside. One of the view it's a DatePicker with displayedComponents: .hourAndMinute. And other one is two Pickers inside HStack. My question is how to make Pickers make look like in system: without white spacing between?
struct MultyPicker: View {
#State var value = 1
#State var value2 = 1
var body: some View {
ZStack(alignment: .bottom) {
Color.black.opacity(0.5)
ZStack {
VStack {
Text("Header")
.font(.title3)
.fontWeight(.bold)
HStack(spacing: 0) {
Picker(selection: $value, label: Text("")) {
ForEach(1..<26) { number in
Text("\(number)")
.tag("\(number)")
}
}
.pickerStyle(WheelPickerStyle())
.compositingGroup()
.clipped(antialiased: true)
Picker(selection: $value2, label: Text("")) {
ForEach(25..<76) { number in
Text("\(number)")
.tag("\(number)")
}
}
.pickerStyle(WheelPickerStyle())
.compositingGroup()
.clipped(antialiased: true)
}
}
.padding()
.background(
RoundedRectangle(cornerRadius: 34)
.foregroundColor(.white)
)
}
.padding(.horizontal)
.padding(.bottom, 50)
}
.edgesIgnoringSafeArea([.top, .horizontal])
}
}
// This extension for correct touching area
extension UIPickerView {
open override var intrinsicContentSize: CGSize {
return CGSize(width: UIView.noIntrinsicMetric, height: super.intrinsicContentSize.height)
}
}
Want to achive looks like that with one grey line in selected value
//
// Test2.swift
// Test
//
// Created by Serdar Onur KARADAĞ on 26.08.2022.
//
import SwiftUI
struct Test2: View {
#State var choice1 = 0
#State var choice2 = 0
var body: some View {
ZStack {
Rectangle()
.fill(.gray.opacity(0.2))
.cornerRadius(30)
.frame(width: 350, height: 400)
Rectangle()
.fill(.white.opacity(1))
.cornerRadius(30)
.frame(width: 300, height: 350)
VStack {
Text("HEADER")
HStack(spacing: 0) {
Picker(selection: $choice1, label: Text("C1")) {
ForEach(0..<10) { n in
Text("\(n)").tag(n)
}
}
.pickerStyle(.wheel)
.frame(minWidth: 0)
.clipped()
Picker(selection: $choice2, label: Text("C1")) {
ForEach(0..<10) { n in
Text("\(n)").tag(n)
}
}
.pickerStyle(.wheel)
.frame(minWidth: 0)
.clipped()
}
}
}
}
}
struct Test2_Previews: PreviewProvider {
static var previews: some View {
Test2()
}
}
SwiftUI multi-component Picker basically consists of several individual Picker views arranged horizontally. Therefore, we start by creating an ordinary Picker view for our first component. I am using Xcode version 13.4.1(iOS 15.0).
import SwiftUI
struct ContentView: View {
#State var hourSelect = 0
#State var minuteSelect = 0
var hours = [Int](0..<24)
var minutes = [Int](0..<60)
var body: some View {
ZStack {
Color.black
.opacity(0.5)
.ignoresSafeArea()
.preferredColorScheme(.light)
Rectangle()
.fill(.white.opacity(1))
.cornerRadius(30)
.frame(width: 300, height: 350)
VStack {
Text("Header")
HStack(spacing: 0) {
Picker(selection: $hourSelect, label: Text("")) {
ForEach(0..<self.hours.count) { index in
Text("\(self.hours[index])").tag(index)
}
}
.pickerStyle(.wheel)
.frame(minWidth: 0)
.compositingGroup()
.clipped()
Picker(selection: $minuteSelect, label: Text("")) {
ForEach(0..<self.minutes.count) { index in
Text("\(self.minutes[index])").tag(index)
}
}
.pickerStyle(.wheel)
.frame(minWidth: 0)
.compositingGroup()
.clipped()
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Output :

Navigating to different views within SwiftUI

In my example code below, I have two tabs and within the main tab (Tab A) there are two "buttons" on the front page to allow the user to navigate to two views (View 1 or View 2) using navigationlinks. Within each of view 1 and view 2 there are further navigation links so my code (purposefully) resets the navigation stack for each view when you switch tabs and then return to the tab. Also, if you navigate to view 1 or view 2 (while still on the main tab (tab A)), tapping the main tab button (tab A) again brings you back to the front page (which presents the two buttons). This behaviour is what I need. The problem I now have is that the navigation links (to view 1 and view 2) don't work as intended. Sometimes clicking the view 1 button takes you to view 2 and sometimes it takes you to view 1. The same happens with the view 2 button. This must have something to do with how I reset the navigation stack for my other needs, but I'm not sure how to solve this. I include some minimal code to show this. Does anyone have an idea how to solve this? Thanks
struct ContentView: View {
#State var activeView: Int = 0
#State var showNavigation: Bool = false
let items = ["View1", "View2"]
var body: some View {
TabView(selection: Binding<Int> (
get: {
activeView
}, set: {
activeView = $0
showNavigation = false
}))
{
NavigationView {
HStack {
VStack {
NavigationLink(
destination: View1(), isActive: $showNavigation, label: {
Rectangle()
.fill(Color.red)
.cornerRadius(12)
.frame(width: 70, height: 70)
}).isDetailLink(false)
Text(items[0])
}
VStack{
NavigationLink(
destination: View2(), isActive: $showNavigation, label: {
Rectangle()
.fill(Color.red)
.cornerRadius(12)
.frame(width: 70, height: 70)
}).isDetailLink(false)
Text(items[1])
}
}.navigationTitle("")
.navigationBarHidden(true)
}
.tabItem {
Image(systemName: "a.circle")
Text("Main")
}
.tag(0)
View3()
.padding()
.tabItem {
Image(systemName: "b.circle")
Text("View 3")
}
.tag(1)
}
}
}
The problem seems to be that you're using the same showNavigation variable for both NavigationLinks.
I've changed the variable around a bit to hold an id and added a custom Binding to keep track of which NavigationLink should be active:
struct ContentView: View {
#State var activeView: Int = 0
#State var activeNavigationLink: Int = 0 //<-- Here
let items = ["View1", "View2"]
func navigationLinkBinding(id: Int) -> Binding<Bool> { //<-- Here
.init { () -> Bool in
activeNavigationLink == id
} set: { (newValue) in
if newValue {
activeNavigationLink = id
} else {
activeNavigationLink = 0
}
}
}
var body: some View {
TabView(selection: Binding<Int> (
get: {
activeView
}, set: {
activeView = $0
activeNavigationLink = 0 //<-- Here
}))
{
NavigationView {
HStack {
VStack {
NavigationLink(
destination: Text("View 1"), isActive: navigationLinkBinding(id: 1), label: { //<-- Here
Rectangle()
.fill(Color.red)
.cornerRadius(12)
.frame(width: 70, height: 70)
}).isDetailLink(false)
Text(items[0])
}
VStack{
NavigationLink(
destination: Text("View 2"), isActive: navigationLinkBinding(id: 2), label: { //<-- Here
Rectangle()
.fill(Color.red)
.cornerRadius(12)
.frame(width: 70, height: 70)
}).isDetailLink(false)
Text(items[1])
}
}.navigationTitle("")
.navigationBarHidden(true)
}
.tabItem {
Image(systemName: "a.circle")
Text("Main")
}
.tag(0)
Text("View 3")
.padding()
.tabItem {
Image(systemName: "b.circle")
Text("View 3")
}
.tag(1)
}
}
}

Show selected tab in TabView in SwiftUI

When using TabView in SwiftUI, what can I do to show the selected Tab like in the following picture?
I've tried creating a VStack within each tab like this:
struct ContentView: View {
#State public var tabViewSelection = 0
var body: some View {
TabView(selection: $tabViewSelection) {
HomeFirstLevel()
.tabItem {
VStack {
Image("HomeIcon")
Rectangle()
.frame(height: 7)
.foregroundColor((tabViewSelection == 0) ? .black : .clear)
}
}.tag(0)
}
}
}
But it's not working.
I can't even seem to add a Rectangle instead of an Image:
HomeFirstLevel()
.tabItem {
Rectangle()
}.tag(0)
Does TabView not accept shapes?
Thanks in advance for the help!
You can not set shape in tabItem. But you can use ZStack to add shape over the tab bar and set the x position.
Here is the demo.
struct ContentViewTabDemo: View {
#State public var tabViewSelection = 0
private var singleTabWidth = UIScreen.main.bounds.width / 5
var body: some View {
ZStack(alignment: .bottomLeading) {
TabView(selection: $tabViewSelection) {
Color.red
.tabItem {
VStack {
Image(systemName: "circle.fill")
}
}.tag(0)
Color.blue
.tabItem {
VStack {
Image(systemName: "heart.fill")
}
}.tag(1)
Color.red
.tabItem {
VStack {
Image(systemName: "circle.fill")
}
}.tag(2)
Color.blue
.tabItem {
VStack {
Image(systemName: "heart.fill")
}
}.tag(3)
Color.red
.tabItem {
VStack {
Image(systemName: "circle.fill")
}
}.tag(4)
}
Rectangle()
.offset(x: singleTabWidth * CGFloat(tabViewSelection))
.frame(width: singleTabWidth, height: 7)
.padding(.bottom, 2)
.animation(.default)
}
}
}

SwiftUI Popover Size is not expanding to fit content

Here is my code
struct ContentView: View {
#State var showingPopover = false
var body: some View {
VStack {
Spacer()
Text("Hello World")
Spacer()
HStack {
Spacer()
Button {
self.showingPopover.toggle()
} label: {
Image(systemName: "plus.circle")
}
.popover(isPresented: $showingPopover) {
List(0..<100) { Text("\($0)") }
}.padding(30)
}
}
}
}
This should produce a really nice popover coming from the plus button. But all I get is a really squashed down popover.
Any idea what I am missing here? Is there a way to tell the popover to expand more (without specifying a size)?
You may use a ScrollView and ForEach instead of a List:
struct ContentView: View {
#State var showingPopover = false
var body: some View {
VStack {
Spacer()
Text("Hello World")
Spacer()
HStack {
Spacer()
Button(action: {
self.showingPopover.toggle()
}) {
Image(systemName: "plus.circle")
}
.padding(30)
}
}
// can be attached to the button as well (as in the question)
.popover(isPresented: $showingPopover,
attachmentAnchor: .point(.bottomTrailing),
arrowEdge: .bottom) {
ScrollView(.vertical, showsIndicators: false) {
ForEach(0 ..< 100) {
Text("\($0)")
}
}
}
}
}
You can provide a custom frame for the List. Also, don't forget to embed List inside a ScrollView if you want it to scroll.
ScrollView {
List(0..<100) {
Text("\($0)")
}
.frame(width: 100, height: 250)
}

SwiftUI: animating between Single and HStack views

Goal:
1- Shows a view (Blue) that covers entire screen
2- When tapped on bottom (top right corner), it shows an HStack animating right side HStack (Green) "Slide Offset animation".
import SwiftUI
struct ContentView: View {
#State var showgreen = false
var body: some View {
NavigationView {
HStack {
Rectangle()
.foregroundColor(.blue)
if showgreen {
Rectangle()
.foregroundColor(.green)
.offset(x: showgreen ? 0 : UIScreen.main.bounds.width)
.animation(.easeInOut)
}
}
.navigationBarItems(trailing:
Button(action: { self.showgreen.toggle() }) {
Image(systemName: "ellipsis")
})
}
.navigationViewStyle(StackNavigationViewStyle())
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
.colorScheme(.dark)
.previewDevice("iPad Pro (12.9-inch) (3rd generation)")
}
}
The code works, however I cannot get the Green "Slide Offset animation" to work. Really appreciate any help! : )
Instead of using the if conditional, you need the green rectangle to be already present, and just offscreen. When showgreen toggles, you need to shrink the size of the blue rectangle, which will make room for the green rectangle.
struct ContentView: View {
#State var showgreen = false
var body: some View {
NavigationView {
HStack {
Rectangle()
.foregroundColor(.blue)
.frame(width: showgreen ? UIScreen.main.bounds.width / 2 : UIScreen.main.bounds.width)
.animation(.easeInOut)
Rectangle()
.foregroundColor(.green)
.animation(.easeInOut)
}
.navigationBarItems(trailing:
Button(action: { self.showgreen.toggle() }) {
Image(systemName: "ellipsis")
})
}
.navigationViewStyle(StackNavigationViewStyle())
}
}