如何绘制自己的NSTabView标签?

coc*_*fan 6 user-interface cocoa nstabview

我想为NSTabViewItems 绘制自己的标签.我的标签应该看起来不同,从左上角开始,而不是居中.

我怎样才能做到这一点?

pan*_*pan 5

可以将 NSTabView 的样式设置为 Tabless,然后使用 NSSegmentedControl 控制它,该 NSSegmentedControl 是 NSSegmentedCell 的子类以覆盖样式和行为。要了解如何执行此操作,请查看这个模拟 Xcode 4 样式选项卡的项目: https: //github.com/aaroncrespo/WILLTabView/


Vla*_*lad 5

绘制选项卡的一种可能方法是使用 NSCollectionView。这是 Swift 4 示例:

TabViewStackController包含TabViewController预先配置的 style.unspecified和 custom TabBarView

class TabViewStackController: ViewController {

   private lazy var tabBarView = TabBarView().autolayoutView()
   private lazy var containerView = View().autolayoutView()
   private lazy var tabViewController = TabViewController()
   private let tabs: [String] = (0 ..< 14).map { "TabItem # \($0)" }

   override func setupUI() {
      view.addSubviews(tabBarView, containerView)
      embedChildViewController(tabViewController, container: containerView)
   }

   override func setupLayout() {
      LayoutConstraint.withFormat("|-[*]-|", forEveryViewIn: containerView, tabBarView).activate()
      LayoutConstraint.withFormat("V:|-[*]-[*]-|", tabBarView, containerView).activate()
   }

   override func setupHandlers() {
      tabBarView.eventHandler = { [weak self] in
         switch $0 {
         case .select(let item):
            self?.tabViewController.process(item: item)
         }
      }
   }

   override func setupDefaults() {
      tabBarView.tabs = tabs
      if let item = tabs.first {
         tabBarView.select(item: item)
         tabViewController.process(item: item)
      }
   }
}
Run Code Online (Sandbox Code Playgroud)

TabBarView包含CollectionView代表选项卡的。

class TabBarView: View {

   public enum Event {
      case select(String)
   }

   public var eventHandler: ((Event) -> Void)?

   private let cellID = NSUserInterfaceItemIdentifier(rawValue: "cid.tabView")
   public var tabs: [String] = [] {
      didSet {
         collectionView.reloadData()
      }
   }

   private lazy var collectionView = TabBarCollectionView()
   private let tabBarHeight: CGFloat = 28
   private (set) lazy var scrollView = TabBarScrollView(collectionView: collectionView).autolayoutView()

   override var intrinsicContentSize: NSSize {
      let size = CGSize(width: NSView.noIntrinsicMetric, height: tabBarHeight)
      return size
   }

   override func setupHandlers() {
      collectionView.delegate = self
   }

   override func setupDataSource() {
      collectionView.dataSource = self
      collectionView.register(TabBarTabViewItem.self, forItemWithIdentifier: cellID)
   }

   override func setupUI() {
      addSubviews(scrollView)

      wantsLayer = true

      let gridLayout = NSCollectionViewGridLayout()
      gridLayout.maximumNumberOfRows = 1
      gridLayout.minimumItemSize = CGSize(width: 115, height: tabBarHeight)
      gridLayout.maximumItemSize = gridLayout.minimumItemSize
      collectionView.collectionViewLayout = gridLayout
   }

   override func setupLayout() {
      LayoutConstraint.withFormat("|[*]|", scrollView).activate()
      LayoutConstraint.withFormat("V:|[*]|", scrollView).activate()
   }
}

extension TabBarView {

   func select(item: String) {
      if let index = tabs.index(of: item) {
         let ip = IndexPath(item: index, section: 0)
         if collectionView.item(at: ip) != nil {
            collectionView.selectItems(at: [ip], scrollPosition: [])
         }
      }
   }
}

extension TabBarView: NSCollectionViewDataSource {

   func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int {
      return tabs.count
   }

   func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem {
      let tabItem = tabs[indexPath.item]
      let cell = collectionView.makeItem(withIdentifier: cellID, for: indexPath)
      if let cell = cell as? TabBarTabViewItem {
         cell.configure(title: tabItem)
      }
      return cell
   }
}

extension TabBarView: NSCollectionViewDelegate {

   func collectionView(_ collectionView: NSCollectionView, didSelectItemsAt indexPaths: Set<IndexPath>) {
      if let first = indexPaths.first {
         let item = tabs[first.item]
         eventHandler?(.select(item))
      }
   }
}
Run Code Online (Sandbox Code Playgroud)

TabViewController用样式预配置的类.unspecified

class TabViewController: GenericTabViewController<String> {

   override func viewDidLoad() {
      super.viewDidLoad()
      transitionOptions = []
      tabStyle = .unspecified
   }

   func process(item: String) {
      if index(of: item) != nil {
         select(itemIdentifier: item)
      } else {
         let vc = TabContentController(content: item)
         let tabItem = GenericTabViewItem(identifier: item, viewController: vc)
         addTabViewItem(tabItem)
         select(itemIdentifier: item)
      }
   }
}
Run Code Online (Sandbox Code Playgroud)

剩下的课。

class TabBarCollectionView: CollectionView {

   override func setupUI() {
      isSelectable = true
      allowsMultipleSelection = false
      allowsEmptySelection = false
      backgroundView = View(backgroundColor: .magenta)
      backgroundColors = [.clear]
   }
}

class TabBarScrollView: ScrollView {

   override func setupUI() {
      borderType = .noBorder
      backgroundColor = .clear
      drawsBackground = false

      horizontalScrollElasticity = .none
      verticalScrollElasticity = .none

      automaticallyAdjustsContentInsets = false
      horizontalScroller = InvisibleScroller()
   }
}

// Disabling scroll view indicators.
// See: /sf/ask/655546741/
private class InvisibleScroller: Scroller {

   override class var isCompatibleWithOverlayScrollers: Bool {
      return true
   }

   override class func scrollerWidth(for controlSize: NSControl.ControlSize, scrollerStyle: NSScroller.Style) -> CGFloat {
      return CGFloat.leastNormalMagnitude // Dimension of scroller is equal to `FLT_MIN`
   }

   override func setupUI() {
      // Below assignments not really needed, but why not.
      scrollerStyle = .overlay
      alphaValue = 0
   }
}

class TabBarTabViewItem: CollectionViewItem {

   private lazy var titleLabel = Label().autolayoutView()

   override var isSelected: Bool {
      didSet {
         if isSelected {
            titleLabel.font = Font.semibold(size: 10)
            contentView.backgroundColor = .red
         } else {
            titleLabel.font = Font.regular(size: 10.2)
            contentView.backgroundColor = .blue
         }
      }
   }

   override func setupUI() {
      view.addSubviews(titleLabel)
      view.wantsLayer = true
      titleLabel.maximumNumberOfLines = 1
   }

   override func setupDefaults() {
      isSelected = false
   }

   func configure(title: String) {
      titleLabel.text = title
      titleLabel.textColor = .white
      titleLabel.alignment = .center
   }

   override func setupLayout() {
      LayoutConstraint.withFormat("|-[*]-|", titleLabel).activate()
      LayoutConstraint.withFormat("V:|-(>=4)-[*]", titleLabel).activate()
      LayoutConstraint.centerY(titleLabel).activate()
   }
}

class TabContentController: ViewController {

   let content: String
   private lazy var titleLabel = Label().autolayoutView()

   init(content: String) {
      self.content = content
      super.init()
   }

   required init?(coder: NSCoder) {
      fatalError()
   }

   override func setupUI() {
      contentView.addSubview(titleLabel)
      titleLabel.text = content
      contentView.backgroundColor = .green
   }

   override func setupLayout() {
      LayoutConstraint.centerXY(titleLabel).activate()
   }
}
Run Code Online (Sandbox Code Playgroud)

这是它的样子:

结果


Mar*_*eau 3

NSTabView 不是 Cocoa 中最可定制的类,但可以对其进行子类化并进行自己的绘图。除了维护选项卡视图项的集合之外,您不会使用超类的太多功能,并且最终将实现许多 NSView 和 NSResponder 方法以使绘图和事件处理正常工作。

最好先看看免费或开源选项卡栏控件之一,我过去使用过PSMTabBarControl,它比实现我自己的选项卡视图子类(这是它所取代的)要容易得多。