NSTabView,即选项卡视图组件,属于APPKit.framework,NSTabViewController中也是包含一个NSTabView来实现的ViewController,NSTabView包含N个选项卡(NSTabViewItem)与多个页面,通过每点击一个选项卡(NSTabViewItem)对应一个页面view,每一个页面view也可以关联一个其他Controlller的view。

XIB中直接使用
首先在主界面XIB中拖拽进来一个NSTabView控件,设置好tab数量及标题
因为在xib中不能存在多个Viewcontroller,想关联ViewController要代码关联。如果是Storyboard使用NSTabViewController直接拖拽关联ViewController。
接着为每一个NSTabViewItem创建独立的ViewController和XIB(注意ViewController需继承自NSViewController类型)
最后需要把界面上的TabViewItem关联到ViewController的view上。
@interface AppDelegate ()
@property (weak) IBOutlet NSWindow *window;
@property (weak) IBOutlet NSTabView *tabView;
@property (nonatomic, strong) OneViewController *oneViewController;
@property (nonatomic, strong) TwoViewController *twoViewController;
@end
@implementation AppDelegate
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
// Insert code here to initialize your application
NSTabViewItem *tabViewItem1 = [self.tabView.tabViewItems objectAtIndex:0];
self.oneViewController = [[OneViewController alloc] initWithNibName:@"OneViewController" bundle:nil];
[tabViewItem1 setView:self.oneViewController.view];
NSTabViewItem *tabViewItem2 = [self.tabView.tabViewItems objectAtIndex:1];
self.twoViewController = [[TwoViewController alloc] initWithNibName:@"TwoViewController" bundle:nil];
[tabViewItem2 setView:self.twoViewController.view];
代码创建
当然也可以用代码来创建(通过NSTabView的addTabViewItem来手动加入NSTabViewItem对象)
NSTabViewItem *detailItem = [[NSTabViewItem alloc]init]; detailItem.view = xxview; [self.tabView addTabViewItem:detailItem];
自定义样式
TabView有几个样式供大家选择
Top Tabs:标签在顶部
Left Tabs:标签在左策
Bottom Tabs:标签在底部
Right Tabs:标签在右侧
Tabless:不显示标签
Tabless with Bezel:不显示标签,view圆角
Tabless with line,不显示标签,显示一条分割线。
自定义TabViewItem与背景
如下图,TabView无边框与背景并且正常显示选项卡。
这种效果其实很简单。把TabView的样式设置为,Tabless:不显示标签。然后在TabView的相应位置增加一个NSSegmentedControl视图。NSSegmentedControl设置下具体多少个选项卡,和相应事件即可。
- (IBAction)segmentControlClicked:(id)segmentControl{
NSInteger index = [segmentControl selectedSegment];
[self.tabView selectTabViewItemAtIndex:index];
}
官方文档
https://developer.apple.com/documentation/appkit/nstabview
转载请注明:天狐博客 » Cocoa开发之NSTabView



