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

问题描述:

我使用swift 4处理macOS。 我有一个tabView控制器与三个标签查看项目。 所有项目视图控制器有不同的大小(宽度/高度)具有动态宽度和高度的选项卡视图控制器

现在我想了解,tabview控制器将更改他自己的大小动画为所选标签视图项目的内容大小。

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

我为您的案例创建了一个快速演示代码。基本上你需要记住每个视图项目的原始大小。当选中标签时,只需调整窗口大小。

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) 


     } 
    } 
} 

enter image description here

+0

非常感谢你:) – Ghost108

+0

@ Ghost108欢迎您:] – brianLikeApple