状态栏添加图标
在系统的菜单栏上添加App的图标
状态栏是MacOSX常驻应用的必争之地,代码如下
NSStatusItem *_statusItem = [[NSStatusBar systemStatusBar] statusItem WithLength:NSVariableStatusItemLength];
[_statusItem setImage:[NSImage imageNamed:@"image"]];
[_statusItem setToolTip:@"额"];
[_statusItemset HighlightMode:YES];
// 设置点击方法
_statusItem.button.action = @selector(selectBtn:);
这里需要注意的是,NSStatusItem最好写到全局属性,不然可能出现神奇的事情
UIButton 设置按钮背景图片
// set up start button
UIImage *greenImage = [[UIImage imageNamed:@"green_button.png"] stretchableImageWithLeftCapWidth:12.0 topCapHeight:0.0];
UIImage *redImage = [[UIImage imageNamed:@"red_button.png"] stretchableImageWithLeftCapWidth:12.0 topCapHeight:0.0];
[startButton setBackgroundImage:greenImage forState:UIControlStateNormal];
[startButton setBackgroundImage:redImage forState:UIControlStateDisabled];
[startButton setEnabled:YES];
NSView中实现鼠标的相关响应(转)
在cocoa中的鼠标事件相比ios中的touch事件要显得复杂一些,ios中可以通过重写touchBegin、touchMove、touchEnd等相应方法便可,或是控制相应的响应链。但在cocoa中却引入了一个TrackingArea(跟踪区域)的概念,你需要继承相应的NSResponder对象(如NSView),在合适的地方添加trackingArea,然后便可以通过重写相应的mouse方法就可以了。
下面举例两种方式实现对整个视图的跟踪:
方法一
- (id)initWithFrame:(NSRect)frameRect {
self = [super initWithFrame:frameRect];
if (self) {
[self addTrackingRect:self.bounds owner:self userData:nil assumeInside:YES];
}
return self;
}
方法二
优点在于可以实现当视图未激活情况下也能响应)
//此方法需要在改变的时候手动调用一次(父类的方法)
- (void)updateTrackingAreas
{
NSArray *trackings = [self trackingAreas];
for (NSTrackingArea *tracking in trackings)
{
[self removeTrackingArea:tracking];
}
//添加NSTrackingActiveAlways掩码可以使视图未处于激活或第一响应者时也能响应相应的方法
NSTrackingArea *trackingArea = [[NSTrackingArea alloc] initWithRect:[self bounds] options:NSTrackingMouseEnteredAndExited|NSTrackingMouseMoved|NSTrackingActiveAlways owner:self userInfo:nil];
[self addTrackingArea:trackingArea];
}
设置WebView随着window窗口增大缩小
[iWebView setUIDelegate:self];
[iWebView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
没有标题栏的NSWindow如何拖动
[[self window] setMovableByWindowBackground:YES];
Mac应用点击关闭按钮就退出程序的方法
方法一:
- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)sender{
return YES;
}
方法二:
NSButton *closeButton = [self window] standardWindowButton:NSWindowCloseButton];
[closeButton setTarget:self];
[closeButton setAction:@selector(closeApplication)];
- (void) closeApplication {
[NSApplication sharedApplication] terminate:nil];
}
NSButton生成自定义Button
NSButton *btnMax =[[NSButton alloc]initWithFrame:CGRectMake(14, 0, 14, 14)];
[btnMax setImage:[NSImage imageNamed:@"max"]];
[btnMax setAlternateImage:[NSImage imageNamed:@"maxDown"]];
[[btnMax cell]setHighlightsBy:NSContentsCellMask];
[btnMax setBordered:NO];
[viewGo addSubview:btnMax];
NSString判断字符是否一样
- (BOOL)hasPrefix:(NSString *)string; 判断前面是否包含子串
- (BOOL)hasSuffix:(NSString *)string; 判断末尾是否包含子串
- (NSRange)rangeOfString:(NSString *)string;第一次出现b包含字符串
NSString [a hasPrefix: ] [a hasSuffix:] 判断开头和结束是否包含子串
- (void)viewDidLoad
{
NSMutableString *a = [[NSMutableString alloc ] initWithString :@"i like long dress"];
NSLog(@"\n a: %@",a);
[a hasPrefix:@"i"] ==YES? NSLog(@"以 i 开头"): NSLog(@"不以 i 开头");
[a hasSuffix:@"hat"] ==YES? NSLog(@"以 hat 结尾"): NSLog(@"不以 hat 结尾");
[a release];
}
文件夹中
NSString *resourcesPath = [[NSBundlemainBundle] resourcePath];
NSString *htmlPath = [resourcesPath stringByAppendingFormat:@"/htdocs/about.html"];
[[webViewmmainFrame] loadRequest:[NSURLRequestrequestWithURL:[NSURLfileURLWithPath:htmlPath]]];
在Documents文件夹里
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"index.html"];
NSURL *url = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[_webView loadRequest:request];
webView中打开链接地址
// 方法一:
[webViewm setMainFrameURL:@"http://www.pc175.com"];
// 方法二:
NSString *urlString =@"http://www.baidu.com";
[[webView mainFrame] loadRequest:[NSURLRequestrequestWithURL:[NSURLURLWithString:urlString]]];
屏蔽WebView右键菜单方法
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
[_webViews setUIDelegate: self];
}
- (NSArray *)webView:(WebView *)sender contextMenuItemsForElement:(NSDictionary *)element defaultMenuItems:(NSArray *)defaultMenuItems{
return nil;
}
NSTableView row 响应双击事件和单击事件 setDoubleAction 和 setAction
-(void)awakeFromNib{
[super awakeFromNib];
[tableView setTarget:self];
[tableView setDoubleAction:NSSelectorFromString(@"doubleClick:")];
//setDoubleAction双击选择事件
[tableView setAction:NSSelectorFromString(@"doubleClick:")];//setAction单击选择事件
}
- (void) doubleClick: (id)sender
{
NSInteger rowNumber = [tableViewclickedRow];
NSLog(@"Double Clicked.%ld ",rowNumber);
}
显示窗口orderFront、隐藏窗口orderOut
- (IBAction)hideWindow:(id)sender{
[theWindow orderOut:sender];
}
- (IBAction)hideWindow:(id)sender{
if ([theWindow isVisible])
[theWindow orderOut:sender];
}
- (IBAction)showWindow:(id)sender{
[theWindow orderFront:sender];
}
NStableView Transparent NStableView透明设置
[[tableView enclosingScrollView] setDrawsBackground:NO];
[tableView setBackgroundColor:[NSColor clearColor]];
NSString与int和float的相互转换
字符串拼接
NSString *newString = [NSString stringWithFormat:@"%@%@",tempA,tempB];
字符转int
int intString = [newString intValue];
int转字符
NSString *stringInt = [NSString stringWithFormat:@"%d",intString];
字符转float
float floatString = [newString floatValue];
float转字符
NSString *stringFloat = [NSString stringWithFormat:@"%f",intString];
获取tag
NSString *tags = [NSStringstringWithFormat:@"%i",[sender tag]];
NSLog(@"%@",tags);
全屏窗口中响应鼠标事件
如果想要全屏窗口中响应鼠标事件,必须重写一下- (BOOL)canBecomeKeyWindow,使其总是返回YES
- (BOOL)canBecomeKeyWindow{
return YES;
}
判断双击
[theEvent clickCount] == 2
if([theEvent clickCount] == 1){
NSLog(@"111");
}else if([theEvent clickCount] == 2){
NSLog(@"222");
}
获取当前时间
NSDate *nows =[NSDatedate];
NSCalendar *gregorian = [[NSCalendaralloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dateComponents = [gregorian components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:nows];
NSInteger hour = [dateComponents hour];
NSInteger minute = [dateComponents minute];
NSInteger second = [dateComponents second];
NSInteger month=[dateComponents month];
NSInteger day=[dateComponents day];
NSLog(@"%@",[NSStringstringWithFormat: @"status%lu",day]);
NSLog Format specifiers for data types数据类型格式规范
Type
Format specifier
Considerations
NSInteger
%ld or %lx
Cast the value to long
NSUInteger
%lu or %lx
Cast the value to unsigned long
CGFloat
%f or %g
%f works for floats and doubles when formatting; but see below warning when scanning
CFIndex
%ld or %lx
The same as NSInteger
pointer
%p
%p adds 0x to the beginning of the output. If you don't want that, use %lx and cast to long.
long long
%lld or %llx
long long is 64-bit on both 32- and 64-bit platforms
unsigned long long
%llu or %llx
unsigned long long is 64-bit on both 32- and 64-bit platforms
隐藏window titlebar
[_windowsetStyleMask:NSBorderlessWindowMask];
解决超链接添加 target=”_blank”之后在WebView中不能打开
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification{
[webViewsetUIDelegate:self];
}
- (WebView *)webView:(WebView *)sender createWebViewWithRequest:(NSURLRequest *)request{
NSLog(@"sss%@",sender);
NSUInteger windowStyleMask = NSClosableWindowMask |
NSMiniaturizableWindowMask |
NSResizableWindowMask |
NSTitledWindowMask;
NSWindow * webWindow = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, 800, 600) styleMask:windowStyleMask backing:NSBackingStoreBuffereddefer:NO];
WebView * newWebView = [[WebView alloc] initWithFrame:[webWindow contentRectForFrameRect:webWindow.frame]];
[newWebView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
[webWindow setContentView:newWebView];
[webWindow center];
[webWindow makeKeyAndOrderFront:self];
[[newWebView mainFrame] loadRequest:request];
return newWebView;
}
隐藏和显示最小化时的图标徽章
OSX的窗口在最小化的时候,在缩略图的右下角会显示一个程序图标徽章。我们可以通过程序来显示和隐藏最小化图标的徽章。方法很简单如下:
// Show minimize icon badge
- (IBAction)showMinimizeBadge:(id)sender {
[[self.windowdockTile] setShowsApplicationBadge:YES];
}
// Remove minimize icon badge
- (IBAction)removeMinimizeBadge:(id)sender {
[[self.windowdockTile] setShowsApplicationBadge:NO];
}
status bar
NSDictionary*titleAttributes =[NSDictionary dictionaryWithObject:[NSColor blueColor] forKey:NSForegroundColorAttributeName];
NSAttributedString* blueTitle =[[NSAttributedString alloc] initWithString:@"myTitle" attributes:titleAttributes];
statusItem =[[[NSStatusBar systemStatusBar] statusItemWithLength:NSSquareStatusItemLength] retain];
[statusItem setAttributedTitle:blueTitle];
[blueTitle release];
退出应用程序事件
-(IBAction)quitAction:(id)sender {
[NSApp terminate:sender];
}
给Dock图标加Badge
// Add badge
- (IBAction)addBadge:(id)sender {
[[NSAppdockTile] setBadgeLabel:[NSStringstringWithFormat:@"%d", random() % 11]];
}
// Remove badge
- (IBAction)removeBadge:(id)sender {
[[NSAppdockTile] setBadgeLabel:nil];
}
加Badge是用NSDockTile类的-setBadgeLabel:方法;移除Badge是把badgeLabel的内容设置为nil。这个方法在10.5以上都可以使用,除非需要兼容10.4以下的OSX--现在似乎已经没有很大的必要了,或者是有其他特别的理由,否则真的很难拒绝使用Cocoa的这个简单的API调用。 :)
更换Dock图标
有很多程序能够动态的修改程序图标,如,Adium和iCal。我们通过代码,我们可以在程序运行的时候动态设置Dock图标。修改图标有两种方法,一种是直接指定一个NSImage对象设置应用程序的图标;另一种是用一个自定义的View,来显示为Dock图标。
// Customize Dock Icon
- (IBAction)changeDockIcon:(id)sender {
[NSAppsetApplicationIconImage:[NSImageimageNamed:@"Icon"]];
}
// Restore Dock Icon
- (IBAction)restoreDockIcon:(id)sender {
[NSAppsetApplicationIconImage:nil];
}
// Draw Dock Icon with Custom View
- (IBAction)changeDockIconWithCustomView:(id)sender {
DockIconView *dockView = [[[DockIconView alloc] init] autorelease];
[[NSApp dockTile] setContentView: dockView];
[[NSAppdockTile] display];
}
用自定义View做图标不能自动刷新,所以如果Dock图标有所改变--如加Badge时,可能需要手动通过-display方法刷新。
上面介绍的两种方法修改的程序图标会在程序退出之后还原为在Info.plist里指定的应用程序图标。要永久的改变程序图标(也就是退出程序的时候也能显示修改后的图标)的方法是创建Dock图标的插件。因为这个话题涉及Bundle相关的内容,在这里就不详述了,详情可以参考苹果的文档,以后有机会我会专门写文章介绍Dock图标插件的话题。
隐藏状态栏
In Xcode, double-click the Info.plist file in the left window.
Add a key named UIStatusBarHidden to Info.plist.
Right-click the value field and set the type to Boolean, and then check True.
NSArray 切分数组
NSString *string=@"oop:ack:bork:greeble:ponies";
NSArray *chunks=[string componentsSeparatedByString:string];
string=[chunks componentsJoinedByString:@":-)"];
//上面得代码行将会创建一个内容为oop:-)ack:-)bork:-)greeble:-)ponies 得NSString字符串
actionSheet xcode
UIActionSheet *actionSheet=[[UIActionSheetalloc] initWithTitle:@"Are you sure"delegate:selfcancelButtonTitle:@"now way"destructiveButtonTitle:@"yes,I'm sure!"otherButtonTitles:nil, nil];
[actionSheet showInView:self.view];
[actionSheet release];