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)
}
}
}
Related
I'm trying to use filled image when it is selected and outlined image when it is deselected. I tried to render the images but still filled
So I thought this would work, but it doesn't:
struct ListTabView: View {
#State private var selectedTab = 0
var body: some View {
NavigationView {
TabView(selection: $selectedTab) {
Text("Tab 1")
.onTapGesture {
self.selectedTab += 1
}
.tabItem {
selectedTab == 0 ? Image(systemName: "star.fill") : Image(systemName: "star")
Text("First")
}
.tag(0)
Text("Tab 2")
.onTapGesture {
self.selectedTab -= 1
}
.tabItem {
selectedTab == 1 ? Image(systemName: "moon.stars.fill") : Image(systemName: "moon.stars")
Text("Second")
}
.tag(1)
}
.accentColor(.pink)
.onAppear {
UITabBar.appearance().barTintColor = .white
}
}
}
}
struct ListTabView_Previews: PreviewProvider {
static var previews: some View {
ListTabView()
}
}
Your code actually works. The issue is something else not documented that I can find. If you use a non .fill variant of an SF Font, the .fill variant will be substituted. Use the following code to test it:
TabView(selection: $selectedTab) {
VStack {
Text("Tab 1")
Text(Image(systemName: "star"))
}
.tabItem {
selectedTab == 0 ? Image(systemName: "star") : Image(systemName: "sun.max")
Text("First")
}
.tag(0)
VStack {
Text("Tab 2")
Text(Image(systemName: "moon.stars"))
}
.tabItem {
selectedTab == 1 ? Image(systemName: "moon.stars") : Image(systemName: "sun.max")
Text("Second")
}
.tag(1)
}
You will note I used plain variants, and yet the filled variant was used. Also, you don't need the .onTap(), but I suspect you added it when the images didn't seem to switch.
You can add this to Image / Label:
Image(systemName: selectedTab == 0 ? "star.fill" : "star")
.environment(\.symbolVariants, selectedTabItemIndex == 0 ? .fill : .none)
It will allow you to set the symbol variants as you would expect it.
I'm working on a Mac app (via Mac Catalyst), and I'm looking for a way to display TabView items in the Touch Bar as well...
I tried with the .touchBar modifier, with the targetEnvironment(macCatalyst) and also with #if os(macOS), but no luck...
Any suggestions?
Here is my code:
import SwiftUI
let furl = URL(fileURLWithPath: "path")
struct ContentView: View {
#State private var selected = 0
#State private var isActive = false
var body: some View {
TabView(selection: $selected) {
NavigationView {
HomeView()
}
.navigationViewStyle(StackNavigationViewStyle())
.tabItem {
Image(systemName: (selected == 0 ? "house.fill" : "house"))
Text("Home")
}.tag(0)
NavigationView {
CategoryView(dm: DownloadManager())
}
.navigationViewStyle(DoubleColumnNavigationViewStyle())
.tabItem {
Image(systemName: (selected == 1 ? "text.justify" : "text.justify"))
Text("Categorie")
}.tag(1)
NavigationView {
GalleryView(dm: DownloadManager())
}
.navigationViewStyle(DoubleColumnNavigationViewStyle())
.tabItem {
Image(systemName: (selected == 2 ? "photo.fill" : "photo"))
Text("Galleria")
}.tag(2)
NavigationView {
FavoritesView()
}
.navigationViewStyle(DoubleColumnNavigationViewStyle())
.tabItem {
Image(systemName: (selected == 3 ? "star.fill" : "star"))
Text("Preferiti")
}.tag(3)
NavigationView {
InfoView()
}
.navigationViewStyle(StackNavigationViewStyle())
.tabItem {
Image(systemName: (selected == 4 ? "info.circle.fill" : "info.circle"))
Text("Informazioni")
}.tag(4)
}
.accentColor(.white)
.onAppear() {
UINavigationBar.appearance().barTintColor = UIColor(red: 112.0/255.0, green: 90.0/255.0, blue: 143.0/255.0, alpha: 1.0)
UITabBar.appearance().barTintColor = UIColor(red: 112.0/255.0, green: 90.0/255.0, blue: 143.0/255.0, alpha: 1.0)
UINavigationBar.appearance().titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
}
}
}
Thank you!
I'm writing a widget with WidgetKit and I want to make the widget's content is clickable. For example, if users click to standings, I want to open the standings tab when the app becomes active.
I tried to use notification between the app and widget but the tap gesture is not working, I added print inside of the tap gesture but it did not appear in the console. Also, I added the same app group to both of them.
WidgetView:
struct LargeWidget : View {
#State var standings : [StandingsTable]
var body: some View {
VStack(alignment:.leading){
if standings.count > 0{
HStack(spacing:5){
Text("#").foregroundColor(.gray)
.frame(width: 30)
Text("Team".localized).foregroundColor(.gray)
Spacer()
Text("_D".localized).foregroundColor(.gray)
.frame(width: 30)
Text("_L".localized).foregroundColor(.gray)
.frame(width: 30)
Text("_W".localized).foregroundColor(.gray)
.frame(width: 30)
Text("_P".localized).foregroundColor(.gray)
.frame(width: 30)
}
Divider()
ForEach(0..<5, id: \.self) { i in
HStack(spacing:5){
Text(standings[i].rank)
.font(.system(size: 15))
.padding(.vertical, 3)
.frame(width: 30)
.background(Color(UIColor.systemBackground))
.cornerRadius(4)
Text(standings[i].name)
.lineLimit(1)
.padding(.leading, 5)
Spacer()
Text(standings[i].drawn)
.frame(width: 30)
Text(standings[i].lost)
.frame(width: 30)
Text(standings[i].won)
.frame(width: 30)
Text(standings[i].points)
.frame(width: 30)
}
.padding(.vertical, 5)
.background(standings[i].name == "Besiktas" ? Color(UIColor.systemGray6) : Color.clear)
.cornerRadius(8)
}
Spacer(minLength: 0)
}else{
Text("Large")
.padding()
}
}.padding()
.onTapGesture {
print("clicked to standings")
DispatchQueue.main.async(execute: {
NotificationCenter.default.post(name: NSNotification.Name("standings"), object: nil, userInfo: nil)
})
}
}
}
and here ContentView in app:
import SwiftUI
extension NSNotification {
static let openStandings = NSNotification.Name.init("standings")
}
struct ContentView: View {
#State var show: Bool = false
var body: some View {
NavigationView{
Text("Hello, world!")
.padding()
}.sheet(isPresented: self.$show) {
VStack{
Text("Notification")
.padding()
}
}
.onReceive(NotificationCenter.default.publisher(for: NSNotification.openStandings))
{ obj in
self.show.toggle()
}
}
}
Screenshot of Widget
Okay I created a new project with SwiftUI Environments (not old way AppDelegate and SceneDelegate).
Then I use Link for tap actions and I got it with .onOpenURL modifier in ContentView. It works :)
ContentView:
import SwiftUI
enum SelectedTab: Hashable {
case home
case standings
case options
}
struct ContentView: View {
#State var selectedTab: SelectedTab = .home
var body: some View {
TabView(selection: self.$selectedTab) {
Text("Home")
.tabItem {
Image(systemName: "house")
.renderingMode(.template)
Text("Home")
}.tag(SelectedTab.home)
Text("Standings")
.tabItem {
Image(systemName: "list.number")
.renderingMode(.template)
Text("Standings")
}.tag(SelectedTab.standings)
Text("Options")
.tabItem {
Image(systemName: "gear")
.renderingMode(.template)
Text("Options")
}.tag(SelectedTab.options)
.onOpenURL { (url) in
if url.absoluteString == "widget-deeplink://standings"{
self.selectedTab = .standings
}
}
}
}
}
Link usage example in Widget:
Link(destination: URL(string: "widget-deeplink://standings")!) {
Text("Link Test")
}
Example
Here is a menu with three items:
This is fine. But what I would like to achieve is:
Menu expands
Then the three images fade-in AFTER the menu is done expanding
I thought maybe adding a 2nd, delayed animation for the opacity might work but instead, it looks like all animation (movement and opacity) gets delayed:
Here is the code:
struct SequenceAnimation_SOQuestion: View {
#State private var show = false
var body: some View {
HStack(spacing: 40) {
Group {
Image(systemName: "pencil")
Image(systemName: "scribble")
Image(systemName: "lasso")
}
.opacity(show ? 1 : 0)
.animation(Animation.default.delay(0.5))
Button(action: { self.show.toggle() }) {
Image(systemName: "line.horizontal.3.decrease")
.rotationEffect(.degrees(-90))
}.offset(x: 10)
}
.padding(20)
.padding(.leading, 40)
.foregroundColor(.white)
.background(Capsule().fill(Color.blue))
.font(.largeTitle)
.offset(x: show ? -70 : -320)
.animation(.default)
}
}
You should add each animation separately, then you can have different animations for each one:
struct ContentView: View {
#State private var isMenuCollapsed = true
#State private var isItemsVisible = false
var body: some View {
HStack(spacing: 40) {
Group {
Image(systemName: "pencil")
Image(systemName: "scribble")
Image(systemName: "lasso")
}
.opacity(isItemsVisible ? 1 : 0)
Button(action: {
withAnimation(Animation.default) {
self.isMenuCollapsed.toggle()
}
withAnimation(Animation.default.delay(0.2)) {
self.isItemsVisible.toggle()
}
}) {
Image(systemName: "line.horizontal.3.decrease")
.rotationEffect(.degrees(-90))
}.offset(x: 10)
}
.padding(20)
.padding(.leading, 40)
.foregroundColor(.white)
.background(Capsule().fill(Color.blue))
.font(.largeTitle)
.offset(x: isMenuCollapsed ? -320 : -70)
}
}
I don't know exactly what kind of animation you want, but i worked something out which may be somewhere around your goal.
I changed the working of the animations. In your 2nd example your images were animation not right so that's what the following line fixes:
struct SequenceAnimation_SOQuestion: View {
#State private var show = false
var body: some View {
HStack(spacing: 40) {
Group {
Image(systemName: "pencil")
Image(systemName: "scribble")
Image(systemName: "lasso")
}
.opacity(show ? 1 : 0)
.animation(!self.show ? .default : Animation.default.delay(0.5))
Button(action: { self.show.toggle() }) {
Image(systemName: "line.horizontal.3.decrease")
.rotationEffect(.degrees(-90))
}.offset(x: 10)
}
.padding(20)
.padding(.leading, 40)
.foregroundColor(.white)
.background(Capsule().fill(Color.blue))
.font(.largeTitle)
.offset(x: show ? -70 : -320)
.animation(!self.show ? Animation.default.delay(0.5) : .default)
}
}
If you provide me a bit more specific information about your goal you're trying to achieve, I can maybe help you.
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
}
// ...
}