文章目录
一、简介
Mac 中常见点击状态栏图标,或者点击按钮,会出现带尖角的视图,就是 NSPopover。
二、创建和使用
下面直接展示代码让大家了解怎么使用:
1、为了省时,直接拉取 NSButton 到 xib , 并将按钮拖线到 .m文件,写下 - (IBAction)btn0OnClick:(id)sender {}
方法。
2、创建 FirstViewController.h
继承自 NSViewController
, 建议勾选同时创建 xib。
这个控制器就是 popover 中显示的内容。我们也可以把 NSPopover 理解为一个容器。
3、在 .m 文件中,创建两个属性,并进行懒加载。
不喜欢懒加载的小伙伴,也可以用我的懒加载自动生成工具:
http://blog.csdn.net/lovechris00/article/details/77448356
@property(nonatomic,strong) NSPopover *firstPopover;
@property(nonatomic,strong) FirstViewController * firstVC;
- (NSPopover *)firstPopover
{
if(!_firstPopover)
{
_firstPopover=[[NSPopover alloc]init];
_firstPopover.appearance = [NSAppearance appearanceNamed:NSAppearanceNameAqua];
_firstPopover.contentViewController = self.firstVC;
_firstPopover.behavior = NSPopoverBehaviorTransient;
}
return _firstPopover;
}
- (FirstViewController *)firstVC
{
if(!_firstVC)
{
_firstVC=[[FirstViewController alloc]init];
}
return _firstVC;
}
4、在按钮方法中调出这个 popOver
- (IBAction)btn0OnClick:(id)sender {
NSButton *button = sender;
//显示在button 下面
[self.firstPopover showRelativeToRect:[button bounds] ofView:button preferredEdge:NSRectEdgeMaxY];
}
5、为了丰富 弹窗的内容,你可以往 FirstViewController.xib 中添加内容测试。
三、细节
1、如何控制 popover 窗口大小?
答:调整 popover 中控制器的大小即可,比如我调整了 xib 的尺寸。
2、NSPopover 的 appearance
系统定义了四种 Standard Appearances
NSAppearanceNameAqua
NSAppearanceNameLightContent
NSAppearanceNameVibrantDark
NSAppearanceNameVibrantLight //默认
效果直接上图了:
3、弹出样式 NSPopoverBehavior
typedef NS_ENUM(NSInteger, NSPopoverBehavior) {
NSPopoverBehaviorApplicationDefined = 0,
NSPopoverBehaviorTransient = 1,
NSPopoverBehaviorSemitransient = 2
};
- 弹出的效果上没有什么区别
- NSPopoverBehaviorApplicationDefined 点击其他地方,不会自动消失。
4、出现的方位 NSRectEdge
typedef NS_ENUM(NSUInteger, NSRectEdge) {
NSRectEdgeMinX = CGRectMinXEdge, //按钮右侧
NSRectEdgeMinY = CGRectMinYEdge, //上方
NSRectEdgeMaxX = CGRectMaxXEdge, //左侧
NSRectEdgeMaxY = CGRectMaxYEdge, //下面
}
5、弹出时按钮的响应
如果popover 上面有按钮,弹出时,按钮可能有外光圈,是因为按钮处于选中状态,和选中状态的 NSTextField 一样。
这时候我们可以如下设置:
btn.focusRingType = NSFocusRingTypeNone;
6、NSTextField 和 NSAppearanceNameVibrantLight 样式的冲突
一个坑: http://www.jianshu.com/p/e00ddf1e8475
问题:“今天开发 iTips,遇到一个很诡异的问题:NSOutlineView 中的 NSTableCellView 中的 NSTextField,始终有一个背景色,无论怎么设置都无法去掉。”
原因:“才发现NSPopover 默认使用 NSAppearanceNameVibrantLight 这种样式,因此带来问题:NSTextField 使用透明背景色,进而就会取 NSPopover 中的背景色,就是图中的问题。”
解决方案:只要将 NSPopover 的主题改为 NSAppearanceNameAqua 即可:
self.view.appearance = NSAppearance(named: NSAppearanceNameAqua)
伊织 2017-09