iOS ---OC中的小知识点(2)

11.拖到视频进度与滑动手势冲突解决办法

#pragma mark UIGestureRecognizerDelegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    UIView *touchView = touch.view;
    
    if ([touchView isKindOfClass:[UISlider class]]) 
    {
        return NO;
    }
    else 
    {
        return YES;
    }
}

12.NSDate 与 NSString 转换

1、将字符串 “Fri Nov 11 09:06:27 +0800 2011” 转换成Date:

    NSDateFormatter *format = [[NSDateFormatter alloc] init];
    NSLocale *enLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en-US"];
    [format setLocale:enLocale];
    [enLocale release];
    [format setDateFormat:@"EEE MMM dd HH:mm:ss ZZZ yyyy"];
    NSDate *dateTime = [format dateFromString:message];
 
将Date转换成字符串:
    NSDate *date = [NSDate date];
    NSString * dateString = [format stringFromDate:date];
//字符串转换成NSDate 需要设置NSLocale 否则真机上会失败。

2、获取当前时间,转化成字符串

   NSDateFormatter * formatter = [[NSDateFormatteralloc]init];
    formatter.dateStyle = NSDateFormatterMediumStyle;
    formatter.timeStyle = NSDateFormatterMediumStyle;
    formatter.locale = [NSLocalecurrentLocale];
    self.timeLabel.text = [formatterstringFromDate:[NSDatedate]];

3、获取月、日、年、时、分、秒

NSDateFormatter *formatter =[[[NSDateFormatteralloc] init] autorelease];
    formatter.dateStyle = NSDateFormatterMediumStyle;
    formatter.timeStyle = NSDateFormatterMediumStyle;
    formatter.locale = [NSLocalecurrentLocale];
    
    NSDate *date = [NSDatedate];
    
    [formatter setTimeStyle:NSDateFormatterMediumStyle];
    NSCalendar *calendar = [[[NSCalendaralloc] initWithCalendarIdentifier:NSGregorianCalendar]autorelease];
    NSDateComponents *comps = [[[NSDateComponentsalloc] init] autorelease];
    NSInteger unitFlags = NSYearCalendarUnit |
    NSMonthCalendarUnit |
    NSDayCalendarUnit |
    NSWeekdayCalendarUnit |
    NSHourCalendarUnit |
    NSMinuteCalendarUnit |
    NSSecondCalendarUnit;
    //int week=0;
    comps = [calendar components:unitFlags fromDate:date];
    int week = [comps weekday];
    int year=[comps year];
    int month = [comps month];
    int day = [comps day];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
//    //This sets the label with the updated time.
    int hour = [comps hour];
    int min = [comps minute];
    int sec = [comps second];
    
    NSLog(@"day%d",day);
    NSLog(@"hour%d",hour);
    NSLog(@"min%d",min);
    NSLog(@"sec%d",sec);

13.数组中存储数据查询

NSMutableDictionary *userDic1 = [NSMutableDictionary dictionaryWithCapacity:10];
    NSMutableDictionary *userDic2 = [NSMutableDictionary dictionaryWithCapacity:10];
    [userDic1 setValue:@"Li" forKey:@"name"];
    [userDic2 setValue:@"Wang" forKey:@"name"];
    
    NSArray *userArray = [NSArray arrayWithObjects:userDic1,userDic2,nil];
    NSPredicate *namePredicate = [NSPredicate predicateWithFormat:@"SELF.name contains[cd] %@ ",@"L"];
    
    NSMutableArray *searchArray = [NSMutableArray arrayWithArray:[userArray filteredArrayUsingPredicate:namePredicate]];
    
    NSLog(@"searchArray  == %@",searchArray);

14.自定义拷贝、粘贴窗口

(1)、重写canBecomeFirstResponder方法
  - (BOOL)canBecomeFirstResponder{
  
  [super canBecomeFirstResponder];
  return YES;
}
(2)、创建自定义UIMenuController
  UIMenuItem *share = [[UIMenuItem alloc] initWithTitle:@"分享" action:@selector(share:)];
   UIMenuItem *email = [[UIMenuItem alloc] initWithTitle:@"邮件" action:@selector(email:)];
   UIMenuItem *print = [[UIMenuItem alloc] initWithTitle:@"打印" action:@selector(print:)];

   UIMenuController *menu = [UIMenuController sharedMenuController];
   [menu setMenuItems:[NSArray arrayWithObjects:share, email,print, nil]];
   [menu setTargetRect:self.frame inView:self.superview];
   [menu setMenuVisible:YES animated:YES];
(3)、判断显示哪个menu
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
  [super canPerformAction:action withSender:sender];
 
  if ( action == @selector(share:) || action == @selector(email:) || action == @selector(print:))
  {
      return YES;    
  }
  else
  {
      return NO;
  }
}

15.iOS本地推送通知方法

可在应用后台执行时,本地弹出推送通知,也可以定时触发推送。
- (void)applicationDidEnterBackground:(UIApplication *)application
{
   
   UIDevice* device = [UIDevice currentDevice];
   
   BOOL backgroundSupported = NO;
   
   if ([device respondsToSelector:@selector(isMultitaskingSupported)])
   {    
       backgroundSupported = device.multitaskingSupported;
   }
   if (backgroundSupported && _bgTask==UIBackgroundTaskInvalid)
   {
       UIApplication *app = [UIApplication sharedApplication];
       
       _bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
       }];  
       
       
       dispatch_async(dispatch_get_main_queue(), ^{
           
           while (app.applicationState==UIApplicationStateBackground && _bgTask!=UIBackgroundTaskInvalid  && [app backgroundTimeRemaining] > 10)  
           {
               [NSThread sleepForTimeInterval:1];
               NSLog(@"background task %d left left  time %d.", _bgTask, (int)[app backgroundTimeRemaining]);
                               
               if ([app backgroundTimeRemaining] < 580)
               {
                   UILocalNotification *localNotif = [[UILocalNotification alloc] init];
                   if (localNotif)
                   {
                       localNotif.alertBody = [NSString stringWithString:@"测试本地通知消息,后台提示功能。"];
                       localNotif.alertAction = NSLocalizedString(@"查看", nil);
                       localNotif.soundName = UILocalNotificationDefaultSoundName;
                       localNotif.applicationIconBadgeNumber = 1;            
                       [application presentLocalNotificationNow:localNotif];
                       [localNotif release];
                       break;
                   }
               }
           }
           NSLog(@"background task %d finished.", _bgTask);     
           [app endBackgroundTask:_bgTask];
           _bgTask = UIBackgroundTaskInvalid;   
       });      
   }
}

16.动态获取UILabel的高度和宽度

在使用UILabel存放字符串时,经常需要获取label的长宽数据,本文列出了部分常用的计算方法。
1.获取宽度,获取字符串不折行单行显示时所需要的长度

CGSize titleSize = [aString sizeWithFont:font constrainedToSize:CGSizeMake(MAXFLOAT, 30)];
注:如果想得到宽度的话,size的width应该设为MAXFLOAT。

2.获取高度,获取字符串在指定的size内(宽度超过label的宽度则换行)所需的实际高度.

CGSize titleSize = [aString sizeWithFont:font constrainedToSize:CGSizeMake(label.frame.size.width, MAXFLOAT) lineBreakMode:UILineBreakModeWordWrap];
注:如果想得到高度的话,size的height应该设为MAXFLOAT。

3.实际编程时,有时需要计算一段文字最后一个字符的位置,并在其后添加图片或其他控件(如info图标),下面代码为计算label中最后一个字符后面一位的位置的方法。

CGSize sz = [label.text sizeWithFont:label.font constrainedToSize:CGSizeMake(MAXFLOAT, 40)];
CGSize linesSz = [label.text sizeWithFont:label.font constrainedToSize:CGSizeMake(label.frame.size.width, MAXFLOAT) lineBreakMode:UILineBreakModeWordWrap];
if(sz.width <= linesSz.width) //判断是否折行
{
        lastPoint = CGPointMake(label.frame.origin.x + sz.width, label.frame.origin.y);  
}
else  
{  
        lastPoint = CGPointMake(label.frame.origin.x + (int)sz.width % (int)linesSz.width,linesSz.height - sz.height);  
} 

你可能感兴趣的:(iOS ---OC中的小知识点(2))