以简单的方式在SwiftUI中为TabView tabItem添加徽章值

时间:2020-04-04 01:23:43

标签: xcode swiftui tabview tabitem

是否可以通过简单的方式为TabView tabItem在SwiftUI中添加徽章值?

喜欢这个(这里是普通的Swift):

import UIKit

class TabBarController: UITabBarController {

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    self.tabBar.items![2].badgeValue = "7"
}

}

谢谢

1 个答案:

答案 0 :(得分:3)

SwiftUI中的TabViewItem上没有徽章计数属性,因此您必须在TabViewItem顶部手动添加ZStack并进行一些计算。

struct ContentView: View {
  @State private var badgeNumber: Int = 10
  private var badgePosition: CGFloat = 1
  private var tabsCount: CGFloat = 1

  var body: some View {
    GeometryReader { geometry in
      ZStack(alignment: .bottomLeading) {
        // TabView
        TabView {
          Text("First View")
            .tabItem {
              Image(systemName: "tray.fill")
              Text("First")
          }
        }

        // Badge View
        ZStack {
          Circle()
            .foregroundColor(.red)

          Text("\(self.badgeNumber)")
            .foregroundColor(.white)
            .font(Font.system(size: 12))
        }
        .frame(width: 20, height: 20)
        .offset(x: ( ( 2 * self.badgePosition) - 1 ) * ( geometry.size.width / ( 2 * self.tabsCount ) ), y: -30)
        .opacity(self.badgeNumber == 0 ? 0 : 1)
      }
    }
  }
}