Graphics简单应用
UIImage *btnImage =[HeadPortraitImage setHeadPortraitImage];
CGFloat width = btnImage.size.width;
CGFloat height = btnImage.size.height;
//开始绘制图片
UIGraphicsBeginImageContext(btnImage.size);
CGContextRef gc = UIGraphicsGetCurrentContext();
绘制Clip区域
CGContextAddEllipseInRect(gc, CGRectMake(0, 0,60, 60)); //圆
CGContextClosePath(gc);
CGContextClip(gc);
//坐标系转换
//因为CGContextDrawImage会使用Quartz内的以左下角为(0,0)的坐标系
CGContextTranslateCTM(gc, 0, height);
CGContextScaleCTM(gc, 1, -1);
CGContextDrawImage(gc, CGRectMake(0, 0, width, height), [btnImage CGImage]);
//结束绘画
UIImage *destImg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[self.userHeadBTN setImage:destImg forState:UIControlStateNormal];

Label根据字符串长度自动适应宽度和高度
//这个frame是初设的,没关系,后面还会重新设置其size。
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0,0,0,0)];
label.numberOfLines = 0;
label.backgroundColor = [UIColor clearColor];
NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:20],};
NSString *str = @"就是这一段难伺候的字符串,不知道长度,所以才要让控件自适应";
CGSize textSize = [str boundingRectWithSize:CGSizeMake(100, 100) options:NSStringDrawingTruncatesLastVisibleLine attributes:attributes context:nil].size;;
[label setFrame:CGRectMake(100, 100, textSize.width, textSize.height)];
label.textColor = [UIColor greenColor];
label.text = str;
[self.view addSubview:label];
关于字符串的一些东西,有些东西可能很少用吧
/*----------------写字符串到文件:writeToFile方法----------------*/
NSString *astring = [[NSString alloc] initWithString:@"This is a String!"];
NSLog(@"astring:%@",astring);
NSString *path = @"astring.text";
[astring writeToFile: path atomically: YES];
[astring release];
/*----------------比较两个字符串----------------*/
//用C比较:strcmp函数
char string1[] = "string!";
char string2[] = "string!";
if(strcmp(string1, string2) = = 0)
{
NSLog(@"1");
}
//compare方法(comparer返回的三种值)
NSString *astring01 = @"This is a String!";
NSString *astring02 = @"This is a String!";
BOOL result = [astring01 compare:astring02] = = NSOrderedSame;
NSLog(@"result:%d",result);
//NSOrderedSame判断两者内容是否相同
NSString *astring01 = @"This is a String!";
NSString *astring02 = @"this is a String!";
BOOL result = [astring01 compare:astring02] = = NSOrderedAscending;
NSLog(@"result:%d",result);
//NSOrderedAscending判断两对象值的大小(按字母顺序进行比较,astring02大于astring01为真)
NSString *astring01 = @"this is a String!";
NSString *astring02 = @"This is a String!";
BOOL result = [astring01 compare:astring02] = = NSOrderedDescending;
NSLog(@"result:%d",result);
//NSOrderedDescending判断两对象值的大小(按字母顺序进行比较,astring02小于astring01为真)
//不考虑大小写比较字符串1
NSString *astring01 = @"this is a String!";
NSString *astring02 = @"This is a String!";
BOOL result = [astring01 caseInsensitiveCompare:astring02] = = NSOrderedSame;
NSLog(@"result:%d",result);
//NSOrderedDescending判断两对象值的大小(按字母顺序进行比较,astring02小于astring01为真)
//不考虑大小写比较字符串2
NSString *astring01 = @"this is a String!";
NSString *astring02 = @"This is a String!";
BOOL result = [astring01 compare:astring02
options:NSCaseInsensitiveSearch | NSNumericSearch] = = NSOrderedSame;
NSLog(@"result:%d",result);
//NSCaseInsensitiveSearch:不区分大小写比较 NSLiteralSearch:进行完全比较,区分大小写 NSNumericSearch:比较字符串的字符个数,而不是字符值。
/*----------------改变字符串的大小写----------------*/
NSString *string1 = @"A String";
NSString *string2 = @"String";
NSLog(@"string1:%@",[string1 uppercaseString]);//大写
NSLog(@"string2:%@",[string2 lowercaseString]);//小写
NSLog(@"string2:%@",[string2 capitalizedString]);//首字母大小
/*----------------在串中搜索子串----------------*/
NSString *string1 = @"This is a string";
NSString *string2 = @"string";
NSRange range = [string1 rangeOfString:string2];
int location = range.location;
int leight = range.length;
NSString *astring = [[NSString alloc] initWithString:[NSString stringWithFormat:@"Location:%i,Leight:%i",location,leight]];
NSLog(@"astring:%@",astring);
[astring release];
/*----------------抽取子串 ----------------*/
//-substringToIndex: 从字符串的开头一直截取到指定的位置,但不包括该位置的字符
NSString *string1 = @"This is a string";
NSString *string2 = [string1 substringToIndex:3];
NSLog(@"string2:%@",string2);
//-substringFromIndex: 以指定位置开始(包括指定位置的字符),并包括之后的全部字符
NSString *string1 = @"This is a string";
NSString *string2 = [string1 substringFromIndex:3];
NSLog(@"string2:%@",string2);
//-substringWithRange: //按照所给出的位置,长度,任意地从字符串中截取子串
NSString *string1 = @"This is a string";
NSString *string2 = [string1 substringWithRange:NSMakeRange(0, 4)];
NSLog(@"string2:%@",string2);
//扩展路径
NSString *Path = @"~/NSData.txt";
NSString *absolutePath = [Path stringByExpandingTildeInPath];
NSLog(@"absolutePath:%@",absolutePath);
NSLog(@"Path:%@",[absolutePath stringByAbbreviatingWithTildeInPath]);
//文件扩展名
NSString *Path = @"~/NSData.txt";
NSLog(@"Extension:%@",[Path pathExtension]);
/*---------------给字符串分配容量----------------*/
//stringWithCapacity:
NSMutableString *String;
//其实很多类都有这个方法,WithCapacity都是置顶容量进行初始化(申请内存)
String = [NSMutableString stringWithCapacity:40];
/*---------------在已有字符串后面添加字符----------------*/
//appendString: and appendFormat:
NSMutableString *String1 = [[NSMutableString alloc] initWithString:@"This is a NSMutableString"];
//[String1 appendString:@", I will be adding some character"];
[String1 appendFormat:[NSString stringWithFormat:@", I will be adding some character"]];
/*--------按照所给出的范围,和字符串替换的原有的字符------*/
//-setString:
NSMutableString *String1 = [[NSMutableString alloc] initWithString:@"This is a NSMutableString"];
[String1 replaceCharactersInRange:NSMakeRange(0, 4) withString:@"That"];
NSLog(@"String1:%@",String1);
/*-------------判断字符串内是否还包含别的字符串(前缀,后缀)-------------*/
//01:检查字符串是否以另一个字符串开头- (BOOL) hasPrefix: (NSString *) aString;
NSString *String1 = @"NSStringInformation.txt";
[String1 hasPrefix:@"NSString"] = = 1 ? NSLog(@"YES") : NSLog(@"NO");
[String1 hasSuffix:@".txt"] = = 1 ? NSLog(@"YES") : NSLog(@"NO");
//02:查找字符串某处是否包含其它字符串 - (NSRange) rangeOfString: (NSString *) aString,这一点前面在串中搜索子串用到过;


Json转字典
+ (NSDictionary )dictionaryWithJsonString:(NSString )jsonString {
if (jsonString == nil) {
return nil;
}
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *err;
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingMutableContainers
error:&err];
if(err) {
NSLog(@”jsonè§£æžå¤±è´¥ï¼š%@”,err);
return nil;
}
return dic;
}
字典转Json
+ (NSString*)dictionaryToJson:(NSDictionary *)dic
{
NSError *parseError = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
监测网络状态
- (BOOL)application:(UIApplication )application didFinishLaunchingWithOptions:(NSDictionary )launchOptions {
//添加一个系统通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
//初始化
self.internetReachability=[Reachability reachabilityForInternetConnection];
//通知添加到Run Loop
[self.internetReachability startNotifier];
[self updateInterfaceWithReachability:_internetReachability];
return YES;
}
回调函数:
- (void) reachabilityChanged:(NSNotification *)note
{
Reachability* curReach = [note object];
NSParameterAssert([curReach isKindOfClass:[Reachability class]]);
[self updateInterfaceWithReachability:curReach];
}
- (void)updateInterfaceWithReachability:(Reachability *)reachability
{
NetworkStatus netStatus = [reachability currentReachabilityStatus];
switch (netStatus) {
case NotReachable:
NSLog(@”====当前网络状态不可达=======”);
break;
case ReachableViaWiFi:
NSLog(@”====当前网络状态为Wifi=======”);
break;
case ReachableViaWWAN:
NSLog(@”====当前网络状态为3G=======”);
break;
}
}
self.navigationController.navigationBar.translucent = NO;
//collectionView内的item不足一屏的时候默认不滚蛋,这句话可设置
collectionView.allowSelection = NO;
改变子视图的层级
- (void)bringSubviewToFront:(UIView *)view;//置顶
- (void)sendSubviewToBack…//置底
视图控制器的指定初始化方法,无论调用哪个方法,改初始化方法都会被触发;
-(instancetype)initWithNibName:(NSString )nibNameOrNil bundle:(NSBundle )nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
//完成本类独有的初始化操作.
}
return self;
}
APPdelegate内:
//也可以让APP在后台活得久一点
- (BOOL)application:(UIApplication )application didFinishLaunchingWithOptions:(NSDictionary )launchOptions {
// 注册后台播放
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayback error:NULL];
// 开启远程事件 -->自动切歌
[application beginReceivingRemoteControlEvents];
return YES;
}
UITextView和UILabel加载HTML:http://www.henishuo.com/uitextview-uilabel-load-html/
UITextView在光标处插入字符串:http://www.henishuo.com/uitextview-cursor-insert-string/
hitTest:withEvent:方法流程:http://www.cnblogs.com/klaus/archive/2013/04/22/3036692.html
触摸事件UITouch的用法 : http://blog.youkuaiyun.com/enuola/article/details/8291402
xml\json解析:http://www.jianshu.com/p/a54d367adb2a
block回调:http://blog.youkuaiyun.com/itpeng523/article/details/24315541
监听程序是否被挂起:http://blog.youkuaiyun.com/sqc3375177/article/details/9466687
摄像头和相册:http://blog.sina.com.cn/s/blog_7b9d64af0101cfd9.html
简单排序:http://blog.sina.com.cn/s/blog_4cd8dd130102v7e4.html
图文混排:http://blog.youkuaiyun.com/zengraoli/article/details/12615993
self.collectionView.alwaysBounceVertical = YES;
当界面内容不超过界面大小时不会滑动,加上面这句话就能滑动了
table去除多余cell
TableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
- (void)scrollToRowAtIndexPath:(NSIndexPath *)indexPath atScrollPosition:(UITableViewScrollPosition)scrollPosition animated:(BOOL)animated。滑动到最后一行,或者用scrollview的setContentOffset滚动到最后。
[tableView scrollToNearestSelectedRowAtScrollPosition:UITableViewScrollPositionBottom animated:YES];
这个是选择哪一行的cell,让该行的cell滑到tableView的最底端
NSIndexPath *indexPath = [NSIndexPath indexPathForItem:13 inSection:0];
[tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
这个是指定哪一行的cell,让该行cell滑到tableView的最底端 !
通过Edge隐藏第一行cell分割线 让他左距屏幕那么宽,右为0,然后就可以隐藏了
if (indexPath.row == 0) {
[cell setSeparatorInset:UIEdgeInsetsMake(0, WidthSize, 0, 0)];
}
核心动画的极简应用
CATransition *animation = [CATransition animation];
animation.type = kCATransitionFade;
animation.duration = 0.4;
[instance.layer addAnimation:animation forKey:nil];
获取当前时间,日期
获取当前时间,日期
NSDate *currentDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@”YYYY/MM/dd hh:mm:ss SS”];
NSString *dateString = [dateFormatter stringFromDate:currentDate];
设置导航栏
[self.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:19], NSForegroundColorAttributeName:[UIColor whiteColor]}];
[[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed:@”navigationBarBg”] forBarMetrics:UIBarMetricsDefault];
状态栏
[[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationNone];
[self.navigationController setNavigationBarHidden:YES animated:NO];
// 隐藏导航栏下的黑线
navBarHairlineImageView.hidden = YES;
// 显示导航栏下的黑线
navBarHairlineImageView.hidden = NO;
拨打网络电话的区别
[self openFuncCommd:@”tel://10086”];//没有弹出提示框,直接打过去
[self openFuncCommd:@”telprompt://10086”];//弹出打电话提示框
去除按钮的点击效果(忽闪一下阴影)
button.adjustsImageWhenHighlighted = NO;
xib情况下设置圆角
layer.cornerRadius layer.masksToBounds
这个方法 静默推送
- (void)application:(UIApplication )application didReceiveRemoteNotification:(NSDictionary )userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler
不管前后台都会走的 前提是 把静默推送打开
自己写的数组去重的方法,玩玩而已
NSMutableArray
- (UIToolbar *)keyBoardToolBar:(long)fieldIndex{
UIToolbar *toolB = [[UIToolbar alloc]init];
[toolB sizeToFit];
toolB.barStyle = UIBarStyleDefault;
//占位的btn,不然不好控制你按钮在toolbar里的位置
UIBarButtonItem *nullBtn = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
UIBarButtonItem *done = [[UIBarButtonItem alloc]initWithTitle:@"Done" style:UIBarButtonItemStylePlain target:self action:@selector(endSelfViewEdit)];
[done setTintColor:UIColorFromRGB(0x333333)];
[toolB setItems:@[nullBtn,done]];
return toolB;
}
_textField.inputAccessoryView = [self keyboardToolBar:1];
输入框有内容时才能点击return键
_textField.enablesReturnKeyAutomatically = YES;