我需要在某个项目中使用NSPageController
,但我不知道它是如何工作的,是否有人有时间通过一些简单的教程向我展示,因为文档没有帮助我。
忘记提及:我正在处理Mac project
(不 iOS
)
答案 0 :(得分:19)
创建新的 Cocoa应用程序 - 项目。在界面构建器中打开MainMenu.xib
,然后将 Image Well 和 Label 对象添加到您的应用程序窗口。还要添加页面控制器对象。
将页面控制器的视图设置为指向图像。
Images.xcassets
我在这个示例项目中使用了三个图像:
为页面控制器,标签和图像良好添加参考渠道。将MyAppDelegate
设为NSPageControllerDelegate
,并为图片添加NSArray
。在此之后,您的MyAppDelegate.h
文件应如下所示:
@interface MyAppDelegate : NSObject <NSApplicationDelegate, NSPageControllerDelegate>
@property (assign) IBOutlet NSWindow *window;
@property (unsafe_unretained) IBOutlet NSPageController *pageController;
@property (weak) IBOutlet NSImageView *imageView;
@property (weak) IBOutlet NSTextField *infoLabel;
@property (nonatomic) NSArray *imageArray;
@end
一些初始化:
- (void)awakeFromNib {
_imageArray = @[ [NSImage imageNamed:@"first"],
[NSImage imageNamed:@"second"],
[NSImage imageNamed:@"third"]];
/* Set delegate for NSPageControl */
[_pageController setDelegate:self];
/* Set arranged objects for NSPageControl */
[_pageController setArrangedObjects:_imageArray];
/* Set transition style, in this example we use book style */
[_pageController setTransitionStyle:NSPageControllerTransitionStyleStackBook];
/* Set info label's text */
NSString *info = [NSString stringWithFormat:@"Image %ld/%ld", ([_pageController selectedIndex]+1), [_imageArray count]];
[_infoLabel setStringValue:info];
}
页面控制器委托方法:
- (void)pageController:(NSPageController *)pageController didTransitionToObject:(id)object {
/* When image is changed, update info label's text */
NSString *info = [NSString stringWithFormat:@"Image %ld/%ld", ([_pageController selectedIndex]+1), [_imageArray count]];
[_infoLabel setStringValue:info];
}
- (NSString *)pageController:(NSPageController *)pageController identifierForObject:(id)object {
/* Returns object's array index as identiefier */
NSString *identifier = [[NSNumber numberWithInteger:[_imageArray indexOfObject:object]] stringValue];
return identifier;
}
- (NSViewController *)pageController:(NSPageController *)pageController viewControllerForIdentifier:(NSString *)identifier {
/* Create new view controller and image view */
NSViewController *vController = [NSViewController new];
NSImageView *iView = [[NSImageView alloc] initWithFrame:[_imageView frame]];
/* Get image from image array using identiefier and set image to view */
[iView setImage:(NSImage *)[_imageArray objectAtIndex:[identifier integerValue]]];
/* Set image view's frame style to none */
[iView setImageFrameStyle:NSImageFrameNone];
/* Add image view to view controller and return view controller */
[vController setView:iView];
return vController;
}
按ctrl
并将鼠标拖动到MyAppDelegate.h
文件中的_pageController,将页面控制器连接到_pageController。