具有动态宽度和高度的选项卡视图控制器

tab view controller with dynamic width and height

我正在为 macOS 使用 swift 4。 我有一个带有三个选项卡视图项的 tabView 控制器。 所有项目视图控制器都有不同的大小(宽度/高度)

现在我想知道,tabview 控制器会将自己的大小动画更改为所选选项卡视图项的内容大小。

但我不知道,我怎么能意识到这一点?

我为您的案例创建了一个快速演示代码。基本上你需要记住每个视图项的原始大小。选择选项卡后,只需调整 window.

的大小
import Cocoa

class MyViewController: NSViewController {
var originalSize: NSSize

init(originalSize: NSSize) {
    self.originalSize = originalSize
    super.init(nibName: nil, bundle: nil)
}

required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")


   }
}

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate, NSTabViewDelegate {
@IBOutlet weak var window: NSWindow!

func applicationDidFinishLaunching(_ aNotification: Notification) {
    // Insert code here to initialize your application
    // Tabview
    let tabView = NSTabView()
    tabView.delegate = self
    tabView.translatesAutoresizingMaskIntoConstraints = false
    self.window.contentView?.addSubview(tabView)
    self.window.contentView?.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[tabView]|", options: [], metrics: nil, views: ["tabView": tabView]))
    self.window.contentView?.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[tabView]|", options: [], metrics: nil, views: ["tabView": tabView]))

    // Tab item views
    let firstVC = MyViewController(originalSize: NSSize(width: 200, height: 200))
    firstVC.view = NSView()
    let firstView = firstVC.view
    firstView.wantsLayer = true
    firstView.layer?.backgroundColor = NSColor.red.cgColor
    let firstItem = NSTabViewItem(viewController: firstVC)
    tabView.addTabViewItem(firstItem)

    let secondVC = MyViewController(originalSize: NSSize(width: 300, height: 300))
    secondVC.view = NSView()
    let secondView = secondVC.view
    secondView.wantsLayer = true
    secondView.layer?.backgroundColor = NSColor.yellow.cgColor
    let secondItem = NSTabViewItem(viewController: secondVC)
    tabView.addTabViewItem(secondItem)

    let thirdVC = MyViewController(originalSize: NSSize(width: 400, height: 400))
    thirdVC.view = NSView()
    let thirdView = thirdVC.view
    thirdView.wantsLayer = true
    thirdView.layer?.backgroundColor = NSColor.green.cgColor
    let thirdItem = NSTabViewItem(viewController: thirdVC)
    tabView.addTabViewItem(thirdItem)
}

func applicationWillTerminate(_ aNotification: Notification) {
    // Insert code here to tear down your application
}

// Delegate
func tabView(_ tabView: NSTabView, didSelect tabViewItem: NSTabViewItem?) {
    if let selectedVC = tabViewItem?.viewController as? MyViewController {
        print("Selected view size is : \(selectedVC.originalSize)")

        var frame = window.frame
        frame.size = selectedVC.originalSize

        window.setFrame(frame, display: true, animate: true)


       }
    }
}