记事笔记

2016-07-18  本文已影响75人  yaya_pangdun

Application

[[UIApplication sharedApplication]openURL:[NSURL URLWithString:@"sms://466453"]];
// badge
[UIApplication sharedApplication].applicationIconBadgeNumber = 4;
//联网指示器
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

获取Windows

UIWindow *window = [[UIApplication sharedApplication].windows objectAtIndex:0];
//弹出的键盘在新的UIWindow上。

管理状态栏

//在UIViewController中管理
-(UIStatusBarStyle)preferredStatusBarStyle
{ 
      //设置为白色 
      //return UIStatusBarStyleLightContent; 
      //默认为黑色 
      return UIStatusBarStyleDefault;
}
#pragma mark-设置状态栏是否隐藏(否)
-(BOOL)prefersStatusBarHidden{ 
      return NO;
}
//整个app管理
[UIApplication sharedApplication].statusBarStyle=UIStatusBarStyleDefault;
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];

[UIApplication sharedApplication].statusBarHidden=YES; //设置状态栏是否隐藏+动画效果 
[[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationFade];
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
[[NSNotificationCenter defaultCenter] addObserver:self
                                      selector:@selector(loginStateChange:)
                                      name:KNOTIFICATION_LOGINCHANGE
                                      object:nil];
if ([UIDevice currentDevice].systemVersion.floatValue >= 7.0) {
        [[UINavigationBar appearance] setBarTintColor:TOPICCOLOR_BLUE];
        [[UINavigationBar appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:TITLECOLOR_BLUE, NSForegroundColorAttributeName, [UIFont fontWithName:@"HelveticaNeue" size:21.0], NSFontAttributeName, nil]];
}
#ifdef DEBUG
#   define MYLog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);
#else
#   define MYLog(...)
#endif
配置pch

//单例化一个类
#define SYNTHESIZE_SINGLETON_FOR_CLASS(classname) \
\
static classname *shared##classname = nil; \
\
+ (classname *)shared##classname \
{ \
    @synchronized(self) \
    { \
        if (shared##classname == nil) \
        { \
            shared##classname = [[self alloc] init]; \
        } \
    } \
    \
    return shared##classname; \
} \
\
+ (id)allocWithZone:(NSZone *)zone \
{ \
    @synchronized(self) \
    { \
        if (shared##classname == nil) \
        { \
            shared##classname = [super allocWithZone:zone]; \
            return shared##classname; \
        } \
    } \  
    \  
    return nil; \  
} \  
\  
- (id)copyWithZone:(NSZone *)zone \  
{ \  
    return self; \  
}

通知

UILocalNotification *localNotification = [[UILocalNotification alloc] init];  
if (localNotification == nil) {  
    return;  
}  
//设置本地通知的触发时间(如果要立即触发,无需设置),这里设置为20妙后  
localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:20];  
//设置本地通知的时区  
localNotification.timeZone = [NSTimeZone defaultTimeZone];  
//设置通知的内容  
localNotification.alertBody = affair.title;  
//设置通知动作按钮的标题  
localNotification.alertAction = @"查看”; 
//设置提醒的声音,可以自己添加声音文件,这里设置为默认提示声 
localNotification.soundName = UILocalNotificationDefaultSoundName; 
//设置通知的相关信息,这个很重要,可以添加一些标记性内容,方便以后区分和获取通知的信息 
NSDictionary *infoDic = [NSDictionary dictionaryWithObjectsAndKeys:LOCAL_NOTIFY_SCHEDULE_ID,@"id",[NSNumber numberWithInteger:time],@"time",[NSNumber numberWithInt:affair.aid],@"affair.aid", nil nil];  
localNotification.userInfo = infoDic;  
//在规定的日期触发通知  
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];  
  
//立即触发一个通知  
//    [[UIApplication sharedApplication] presentLocalNotificationNow:localNotification];  
[localNotification release];

本地存储

NSUserDefaults支持的数据格式有:NSNumber(Integer、Float、Double),NSString,NSDate,NSArray,NSDictionary,BOOL类型

NSString *myString = @"enuola";  
int myInteger = 100;  
float myFloat = 50.0f;  
double myDouble = 20.0;  
NSDate *myDate = [NSDate date];  
NSArray *myArray = [NSArray arrayWithObjects:@"hello", @"world", nil];  
NSDictionary *myDictionary = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"enuo", @"20", nil] forKeys:[NSArray arrayWithObjects:@"name", @"age", nil]];

NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];

//设置
[userDefaults setInteger:myInteger forKey:@"myInteger"];
[userDefaults setObject:myString forKey:@"myString"];
[userDefaults setObject:myDate forKey:@"myDate"];
[userDefaults synchronize];

//获取
NSInteger myInteger = [userDefaultes integerForKey:@"myInteger"];
float myFloat = [userDefaultes floatForKey:@"myFloat"];
NSString *myString = [userDefaultes stringForKey:@"myString"];
NSArray *myArray = [userDefaultes arrayForKey:@"myArray"];
NSDate *myDate = [userDefaultes valueForKey:@"myDate"];
//删除
[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"port_uptime"];

数据库

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [paths objectAtIndex:0];
NSString *dbPath = [documentDirectory stringByAppendingPathComponent:@"LocalDataBase.db"];
FMDatabase *db = [FMDatabase databaseWithPath:dbPath] ;

导航栏

[[UIBarButtonItem alloc] initWithCustomView:groupBtn];
self.navigationItem.leftBarButtonItem

[self.navigationController popViewControllerAnimated:YES];

- (void)agentButton{
    AgentOptionViewController *agnetVC = [[AgentOptionViewController alloc] init];
    agnetVC.title = @"代销列表";
    agnetVC.userid = _userId;
    [self.navigationController pushViewController:agnetVC animated:YES];
}
-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
   self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
   //创建根视图控制器
   RootViewController *rootView = [[RootViewController alloc] init];
   
   UINavigationController *navigationVC = [[UINavigationController alloc] initWithRootViewController:rootView];

   self.window.RootViewController = navigationVC;

}

//navigationController属性
viewControllers //所有处于栈中的控制器
topViewControllers //位于栈顶的控制器
visibleViewController //当前正在显示的控制器
navigationBar //导航条
//UINavigationBar处理能管理一组UINavigationItem
//UINavigationBar也是以栈的方式管理一组UINavigationItem。提供push和pop操作item

//在各个viewController中可以获取navigationController
self.navigationController
//控制视图方法
//将当前栈顶视图控制器出栈销毁
[self.navigationController popViewControllerAnimated:YES];
[self.navigationController popToRootViewControllerAnimated:YES];

[self.navigationController popToViewController:self.navigationController.viewControllers.firstObject animated:YES];

[self.navigationController pushViewController:xxx animated:YES];

UINavigationItem属于MVC中的M,封装了要显示在UiNavigationBar上的数据

下面的栏目

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    RootViewController *rootVC = [[RootViewController alloc] init];

    rootVC.tabBarItem.title = @"first";
    rootVC.tabBarItem.image = [[UIImage imageNamed:@"first.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        rootVC.tabBarItem.selectedImage = ...;
    SecondViewController *secVC = [[SecondViewController alloc] init];
    secVC.tabBarItem.title = @"second";
    secVC.tabBarItem = [[UITabBarItem alloc] initWithTabBarSystemItem:UITabBarSystemItemDownloads tag:2];
    /* 更多样式,任你来选: 
    UITabBarSystemItemMore, 
    UITabBarSystemItemFavorites, 
    UITabBarSystemItemFeatured, 
    UITabBarSystemItemTopRated, 
    UITabBarSystemItemRecents, 
    UITabBarSystemItemContacts, 
    UITabBarSystemItemHistory, 
    UITabBarSystemItemBookmarks, 
    UITabBarSystemItemSearch, 
    UITabBarSystemItemDownloads, 
    UITabBarSystemItemMostRecent, 
    UITabBarSystemItemMostViewed, 
    */
    item0 = [[UITabBarItem alloc] initWithTitle:@"首页" image:[[UIImage imageNamed:@"Home_normal"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] selectedImage:[[UIImage imageNamed:@"Home_selected"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
    UITabBarController *tabBarController = [[UITabBarController alloc] init];
    tabBarController.viewControllers = [NSArray arrayWithObjects:rootVC, secVC, nil];

    tabBarController.tabBar.tintColor = [UIColor yellowColor];
    tabBarController.tabBar.barTintColor = [UIColor redColor];
    tabBarController.tabBar.backgroundImage = [UIImage imageNamed:@"tabBar.png"];

    self.window.RootViewController = tabBarController;
}

校验

@implementation NSString (Valid)
-(BOOL)isChinese{
    NSString *match=@"(^[\u4e00-\u9fa5]+$)";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF matches %@", match];
    return [predicate evaluateWithObject:self];
}
@end

网络

manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:[self baseUrl]]];
//manager = [AFHTTPSessionManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFXMLParserResponseSerializer serializer];

manager.requestSerializer.stringEncoding = NSUTF8StringEncoding;

manager.responseSerializer.acceptableContentTypes = [NSSet setWithArray:@[@"application/json",
                                                                              @"text/html",
                                                                              @"text/json",
                                                                              @"text/plain",
                                                                              @"text/javascript",
                                                                              @"text/xml",
                                                                              @"image/*"]];
manager.requestSerializer.timeoutInterval = sg_timeout;
manager.operationQueue.maxConcurrentOperationCount = 3;

唯一标识

NSString *adld = [[[ASIdentifierManager sharedManager] advertisingIdentifier]UUIDString];

手机信息获取

UIDevice *myDevice = [UIDevice alloc] init]

tableView

AgentIITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"agentiicell"];
if(!cell) {
      cell = [[[NSBundle mainBundle] loadNibNamed:@"AgentIITableViewCell"owner:self options:nil]lastObject];
}

查看代码执行时间和数组循环

double date_s = CFAbsoluteTimeGetCurrent(); 
for (int i = 0; i < test.count; i ++) { 
      sum += [test[i] integerValue]; 
} 
double date_current = CFAbsoluteTimeGetCurrent() - date_s;

for (NSNumber *num in test) { 
      sum += [num integerValue]; 
}

[test enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { 
      sum += [obj integerValue]; 
}];

字典遍历

NSArray *keys = [testDictionary allKeys]; 
for (NSString *key in keys) { 
      NSString *Value = testDictionary[key]; 
}

[testDictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { 

}];;

tableview cell重用问题

// 删除所有重用cell的所有子视图
while ([cell.contentView.subviews lastObject] != nil)  
{  
      [(UIView*)[cell.contentView.subviews lastObject] removeFromSuperview];  
}  

设置字体

[[UIBarItem appearance] setTitleTextAttributes: 
      [NSDictionary dictionaryWithObjectsAndKeys: 
            [UIColor colorWithRed:220.0/255.0 green:104.0/255.0 blue:1.0/255.0 alpha:1.0], UITextAttributeTextColor, 
            [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0], UITextAttributeTextShadowColor, 
            [NSValue valueWithUIOffset:UIOffsetMake(0, 1)], UITextAttributeTextShadowOffset, 
            [UIFont fontWithName:@"AmericanTypewriter" size:0.0], UITextAttributeFont, 
            nil] 
      forState:UIControlStateNormal];

ImageView的contentMode

实例

跳转样式改变

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    self.hidesBottomBarWhenPushed = YES;
}

- (void)viewWillDisappear:(BOOL)animated{
    
    [super viewWillDisappear:animated];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:YES];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

设置模糊效果

// 创建显示图片
UIImageView * imageView = [[UIImageView alloc] init];
/** 毛玻璃特效类型 * UIBlurEffectStyleExtraLight, * UIBlurEffectStyleLight, * UIBlurEffectStyleDark */ 
UIBlurEffect * blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];// 毛玻璃视图
UIVisualEffectView * effectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];//添加到要有毛玻璃特效的控件中
effectView.frame = imageView.bounds;
[imageView addSubview:effectView];//设置模糊透明度
effectView.alpha = .5f;

UIView及其子类重绘drawRect

永远不要去调用drawRect,因为drawRect不是让你调用的,而是系统会去调用的.

//重绘的时候调用这两个函数
//-(void)setNeedsDisplay;
//-(void)setNeedsDisplayInRect:(CGRect)aRect;
-(void)drawRect:(CGRect)rect 
{
      [super drawRect];
      //typedef struct CGContext *CGContextRef;
      CGContextRef context = UIGraphicsGetCurrentContext();//标准第一行

      CGContextMoveToPoint(context , 75 , 10);
      CGContextAddLineToPoint(context , 160 ,150);
      CGContextAddLineToPoint(context , 10 ,150);

//默认使用当前的CGContextRef,所以不用设置
      [ [ UIColor greenColor] setFill];
      [ [ UIColor redColor] setStroke];

      CGContextDrawPath(context , kCGPathFillStroke);
     // 参数kCGPathFillStroke是常量标志,表示描边和填充还是仅描边或仅填充.
}

其实还可以建立一个轨迹,保存到一个轨迹变量CGPath,使用完之后还能交给其他环境继续用,

drawLayer

-(void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx {
    [super drawLayer:layer inContext:ctx];
}

验证手机号

- (BOOL)isValidateMobile:(NSString *)mobile
{
    //手机号以13, 15,18开头,八个 \d 数字字符
//    NSString *phoneRegex = @"^((1[0-9][0-9])|(1[0-9][0-9,\\D])|(1[0-9][0,0-9]))\\d{8}$";
    NSString *phoneRegex = @"^(1)\\d{10}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    return [phoneTest evaluateWithObject:mobile];
}

加载第三方bundle

NSBundle *bundle =[[NSBundle mainBundle] pathForResource:"IQKeyboardManager" ofType=@"bundle"]];
#加载这个bundle中的文件
#ios >= 8.0
imageLeftArrow = [UIImage imageNamed:@"IQButtonBarArrowLeft" inBundle:bundle compatibleWithTraitCollection:nil];
//ios <8.0
NSString *leftArrow = [bundle pathForResource:@"IQButtonBarArrowLeft.png" ofType:nil];
imageLeftArrow = [UIImage imageWithContentsOfFile:leftArrow];

取消delegate

[[EaseMob sharedInstance].chatManager removeDelegate:self];

判断app是否活跃状态

BOOL isAppActivity = [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive;
上一篇下一篇

猜你喜欢

热点阅读