Mac 随意记录

今天做了个实验,在子线程中发通知,主线程中依旧可以瞬间响应,所以,在 global queen 中发通知,在main queen中收消息,也是不会有任何问题的.



状态栏添加图标

在系统的菜单栏上添加App的图标

NSStatusItem *_statusItem = [[NSStatusBarsystemStatusBar] statusItemWithLength:NSVariableStatusItemLength];

[_statusItemsetImage:[NSImageimageNamed:@"stopplay"]];
[_statusItemsetToolTip:@"吧啦吧啦吧啦吧啦吧啦"];
[_statusItemsetHighlightMode:YES];

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窗口增大缩小

//设置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];

遍历父视图上的button

//*** childScroView 为父视图
for (UIView * thebtn in [childScroView subviews]) {
    if ([thebtn isKindOfClass:[UIButton class]]) {
        //***改变字体颜色
        [(UIButton *)thebtn setTitleColor:[UIColor redColor]forState:UIControlStateNormal];
        //***改变背景
        [(UIButton *)thebtn setBackgroundImage:nil forState:UIControlStateNormal];
    }
}

旋转view 设置View横屏

self.view.transform = CGAffineTransformIdentity;
self.view.transform = CGAffineTransformMakeRotation(M_PI*1.5);

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];
}

UIWebView背景透明

// set background transparent, also can set it in nib file
webView_.backgroundColor = [UIColor clearColor];
webView_.opaque = NO;

隐藏拖拽webview时上下的两个有阴影效果的subview

// remove shadow view when drag web view
for (UIView *subView in [webView_ subviews]) {
    if ([subView isKindOfClass:[UIScrollView class]]) {
        for (UIView *shadowView in [subView subviews]) {
            if ([shadowView isKindOfClass:[UIImageView class]]) {
                shadowView.hidden = YES;
            }
        }
    }
}

禁用UIWebView拖拽时的反弹效果

// disable view bounce
[(UIScrollView *)[[webView_ subviews] objectAtIndex:0] setBounces:NO];

禁用UIWebView拖拽

// disable touch move
<script type="text/javascript">
document.ontouchmove = function(e) {
e.preventDefault();
}
</script>

加载html

UIWebView加载本地html

// get html file path
NSString *path = [[NSBundle mainBundle] pathForResource:@"about" ofType:@"html"];
[webView_ loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]]];

加载网络URL:

NSURL *url = [NSURL URLWithString:@"http://localhost:8080/jmDemo/index.html"]; 
NSURLRequest *request = [NSURLRequest requestWithURL:url];  
[_webView loadRequest:request];

加载本地html文件

NSString *path = [[NSBundle mainBundle] pathForResource:@"indedx" ofType:@"html"];  
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]];  
[_webView loadRequest:request];

文件夹中

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的相互转换

  1. 字符串拼接
    NSString *newString = [NSString stringWithFormat:@"%@%@",tempA,tempB];
  2. 字符转int
    int intString = [newString intValue];
  3. int转字符
    NSString *stringInt = [NSString stringWithFormat:@"%d",intString];
  4. 字符转float
    float floatString = [newString floatValue];
  5. float转字符
    NSString *stringFloat = [NSString stringWithFormat:@"%f",intString];

全屏窗口中响应鼠标事件

如果想要全屏窗口中响应鼠标事件,必须重写一下- (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图标插件的话题。

隐藏状态栏

  1. In Xcode, double-click the Info.plist file in the left window.
  2. Add a key named UIStatusBarHidden to Info.plist.
  3. Right-click the value field and set the type to Boolean, and then check True.

加载View

YellowViewController *yellowController=[[YellowViewControlleralloc] initWithNibName:@"YellowView"bundle:nil];
self.yellowViewController =yellowController;
[yellowController release];
blueViewController =[[BlueViewControlleralloc]init];
[yellowViewController.viewremoveFromSuperview];
[self.viewinsertSubview:blueViewController.viewatIndex:0];

自定义按钮

UIImage *buttonImageNormal = [UIImage imageNamed:@"whiteButton.png"];
UIImage *stretchableButtonImageNormal = [buttonImageNormal stretchableImageWithLeftCapWidth:12 topCapHeight:0];
[doSomethingButton setBackgroundImage:stretchableButtonImageNormal
forState:UIControlStateNormal];
UIImage *buttonImagePressed = [UIImage imageNamed:@"blueButton.png"];
UIImage *stretchableButtonImagePressed = [buttonImagePressed
stretchableImageWithLeftCapWidth:12 topCapHeight:0];
[doSomethingButton setBackgroundImage:stretchableButtonImagePressed
forState:UIControlStateHighlighted];

NSArray 切分数组

NSString *string=@"oop:ack:bork:greeble:ponies";
NSArray *chunks=[string componentsSeparatedByString:string];
string=[chunks componentsJoinedByString:@":-)"];
//上面得代码行将会创建一个内容为oop:-)ack:-)bork:-)greeble:-)ponies 得NSString字符串

 
    

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值