1、色值的随机值:
- #define kColorValue arc4random_uniform(256)/255.0
-
- view.backgroundColor = [UIColor colorWithRed:kColorValue green: kColorValue blue: kColorValue alpha: 0.5];
2、定时器的使用:
- [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(fromOutToInside) userInfo:nil repeats:YES];
3、退回键盘触发方法
- - (BOOL)textFieldShouldReturn:(UITextField *)textField;{
- [textField resignFirstResponder];
- return YES;
- }
4、点击空白回收键盘
- - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
- for (int i = 0; i < 5; i ++ ) {
- [field resignFirstResponder];
- }
5、UILabel切圆角,下面两个同时才能显示
label.layer.cornerRadius = 10;//切圆角
label.layer.masksToBounds = YES;
6、 UITextField文本框类型 (圆角)
textField.borderStyle = UITextBorderStyleRoundedRect;
7、定时器
- [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(printHelloword) userInfo:nil repeats:YES];
8、UITextField 文本框的叉号,X
- _field.clearButtonMode = UITextFieldViewModeAlways;
9、设置导航默认标题的颜色及字体大小
- self.navigationController.navigationBar.titleTextAttributes = @{UITextAttributeTextColor: [UIColor whiteColor],
- UITextAttributeFont : [UIFont boldSystemFontOfSize:18]};
11、身份证号处理
- - (NSString *)ittemDisposeIdcardNumber:(NSString *)idcardNumber {
-
- NSString *xinghaoStr = @"";
-
- for (int i = 0; i < idcardNumber.length - 7; i++) {
- xinghaoStr = [xinghaoStr stringByAppendingString:@"*"];
- }
-
- idcardNumber = [NSString stringWithFormat:@"%@%@%@",[idcardNumber substringToIndex:3],xinghaoStr,[idcardNumber substringFromIndex:idcardNumber.length-4]];
-
- return idcardNumber;
- }
----------------------------------------------------------------------------------------------------------
12、//调整字间距
- CFNumberRef num = CFNumberCreate(kCFAllocatorDefault,kCFNumberSInt8Type,&number;);
- [attributedString addAttribute:(id)kCTKernAttributeName value:(__bridge id)num range:NSMakeRange(0, [attributedString length])];
-
- [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [_messageLabel.text length])];
- _messageLabel.attributedText = attributedString;
----------------------------------------------------------------------
13、ios8适配地图授权问题
iOS8修改了位置设置里的内容,增加了一套状态(使用中可用/通常可用),所以以前的CLLcationManage的注册后,
- location = [[CLLocationManager alloc] init];
- location.delegate= self;
- [locationrequestAlwaysAuthorization];
在Plist中追加下面两个字段 (必须有,最少一个,内容是系统ALert的文言,文言可为空)
- - (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
- { switch (status) {
- casekCLAuthorizationStatusNotDetermined:
- if ([location respondsToSelector:@selector(requestAlwaysAuthorization)]) {
- [locationrequestAlwaysAuthorization];
- }
- break;
- default:
- break; }
- }
----------------------------------------------------------------------
14、一段文字设置多种字体颜色
//设置不同字体颜色
- -(void)fuwenbenLabel:(UILabel *)labell FontNumber:(id)font AndRange:(NSRange)range AndColor:(UIColor *)vaColor
- {
- NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:labell.text];
-
- [str addAttribute:NSFontAttributeName value:font range:range];
-
- [str addAttribute:NSForegroundColorAttributeName value:vaColor range:range];
- labell.attributedText = str;
- }
----------------------------------------------------------------------
15、由身份证号码返回性别
- -(NSString *)sexStrFromIdentityCard:(NSString *)numberStr{
- NSString *result = nil;
-
- BOOL isAllNumber = YES;
-
- if([numberStr length]<17)
- return result;
-
-
- NSString *fontNumer = [numberStr substringWithRange:NSMakeRange(16, 1)];
-
-
- const charchar *str = [fontNumer UTF8String];
- const charchar *p = str;
- while (*p!='\0') {
- if(!(*p>='0'&&*p<='9'))
- isAllNumber = NO;
- p++;
- }
- if(!isAllNumber)
- return result;
- int sexNumber = [fontNumer integerValue];
- if(sexNumber%2==1)
- result = @"男";
-
- else if (sexNumber%2==0)
- result = @"女";
-
- return result;
- }
----------------------------------------------------------------------
16、iphone开发之获取系统字体
- + (NSArray*)getAllSystemFonts;
- {
- NSMutableArray *array = [[[NSMutableArray alloc] init] autorelease];
- NSArray* familys = [UIFont familyNames];
-
- for (id obj in familys) {
- NSArray* fonts = [UIFont fontNamesForFamilyName:obj];
- for (id font in fonts)
- {
- [array addObject:font];
- }
- }
- return array;
- }
- + (UIFont*)getCurrentFont
- {
-
- UIFont *font = [UIFont systemFontOfSize:[UIFont systemFontSize]];
- return font;
- }
----------------------------------------------------------------------
17、输入字体,内容。自动算范围
内容:字符串,输入字体大小,和需要多宽
- CGSize size1 = [内容 sizeWithFont:[UIFont boldSystemFontOfSize:13] constrainedToSize:CGSizeMake(宽度, 10000)];
- -(CGFloat)getHeight:(NSString *)text andWidth:(CGFloat)width andFont:(UIFont *)font
- {
- CGRect frame = [text boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options:NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:font} context:nil] ;
- return frame.size.height ;
- }
18、#region 将Base64编码的文本转换成普通文本
-
-
-
-
-
- public static string Base64StringToString(string base64)
- {
- if (base64 != "")
- {
- char[] charBuffer = base64.ToCharArray();
- byte[] bytes = Convert.FromBase64CharArray(charBuffer, 0, charBuffer.Length);
- string returnstr = Encoding.Default.GetString(bytes);
- return returnstr;
- }
- else
- {
- return "";
- }
- }
- #endregion
- #region 字符串转为base64字符串
- public static string changebase64(string str)
- {
- if (str != "" && str != null)
- {
- byte[] b = Encoding.Default.GetBytes(str);
- string returnstr = Convert.ToBase64String(b);
- return returnstr;
- }
- else
- {
- return "";
- }
- }
- #endregion
19、获取文件路径
- NSString *filePath = [[NSBundle mainBundle]pathForResource:@"Contacts.plist" ofType:nil];
20、修改title的字体颜色
- NSDictionary *dic = @{NSForegroundColorAttributeName : [UIColor whiteColor]};
- self.navigationController.navigationBar.titleTextAttributes = dic;
21、添加头像的方法
//调用添加手势的方法
//给aImageView 视图添加轻拍手势
- - (void)addTapGesture{
- UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleTap : )];
-
- [self.aview.aImageView addGestureRecognizer:tap];
- [tap release];
-
- }
//实现轻拍手势的方法
- - (void)handleTap : (UITapGestureRecognizer *)tap{
-
- UIActionSheet *actionSheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"拍照" otherButtonTitles:@"从手机中选择", nil nil];
-
- [actionSheet showInView:self.view];
- [actionSheet release];
- }
- - (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
- switch (buttonIndex) {
- case 0:
-
- NSLog(@"拍照");
- [self pickerPictureFromCamera];
- break;
- case 1:
-
- NSLog(@"从相册中读取照片");
- [self pickerPictureFormPhotoAlbum];
- break;
- default:
- break;
- }
-
- }
//拍照
- - (void)pickerPictureFromCamera{
-
- BOOL isCameera = [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront];
-
-
- if (!isCameera) {
- NSLog(@"没有摄像头可以使用");
- return;
- }
-
- UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init];
-
- imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
-
- imagePicker.allowsEditing = YES;
-
- imagePicker.delegate = self;
-
- [self presentViewController:imagePicker animated:YES completion:nil];
- [imagePicker release];
-
- }
//从相册中取出相片
- - (void)pickerPictureFormPhotoAlbum{
- UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init];
-
- imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
-
- imagePicker.allowsEditing = YES;
-
- imagePicker.delegate = self;
-
- [self presentViewController:imagePicker animated:YES completion:nil];
- [imagePicker release];
-
- }
- - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
-
- self.aview.aImageView.image = [info objectForKey:UIImagePickerControllerEditedImage];
-
- [self dismissViewControllerAnimated:YES completion:nil];
- }
================================================================================
22.NSUserDefaults适合存储轻量级的本地数据,比如要保存一个登陆界面的数据,用户名、密码之类的,个人觉得使用NSUserDefaults是首选。下次再登陆的时候就可以直接从NSUserDefaults里面读取上次登陆的信息咯。
因为如果使用自己建立的plist文件什么的,还得自己显示创建文件,读取文件,很麻烦,而是用NSUserDefaults则不用管这些东西,就像读字符串一样,直接读取就可以了。
NSUserDefaults支持的数据格式有:NSNumber(Integer、Float、Double),NSString,NSDate,NSArray,NSDictionary,BOOL类型
23.封装一个解析的方法:
//封装一个解析的方法
- - (void)parserData : (NSData *)data{
-
- NSMutableDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
-
-
- NSArray *array = dataDic[@"results"];
-
- for (NSDictionary *dic in array) {
-
- Business *bus = [[Business alloc]init];
-
-
- [bus setValuesForKeysWithDictionary:dic];
-
-
- [self.dataSource addObject:bus];
-
- [bus release];
-
- }
-
- [self.tableView reloadData];
- }
24、
'-[Person encodeWithCoder:]: unrecognized selector sent to instance 0x7fc831d9c880’ 方法没实现
25、计算字符串的大小:
- + (CGSize)getStringSize:(NSString *)text strMaxWidth:(CGFloat )width fontSize:(UIFont *)fontSize{
- CGSize constraint = CGSizeMake(width, MAXFLOAT);
- NSDictionary *dict = [NSDictionary dictionaryWithObject:fontSize forKey: NSFontAttributeName];
- CGSize size = CGSizeZero;
- if (isAboveIOS7) {
- size = [text boundingRectWithSize:constraint
- options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
- attributes:dict
- context:nil].size;
- return size;
- }
- size = [text sizeWithFont:fontSize
- constrainedToSize:constraint
- lineBreakMode:NSLineBreakByWordWrapping];
-
- return size;
- }
26、storyboard传值:
- - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
-
-
- RootViewController *rootVC = [segue sourceViewController];
-
-
-
- DetailViewController *detailVC = [segue destinationViewController];
-
- detailVC.string = rootVC.textField.text;
- }
27.赋值方法中基本数据类型转字符串
- self.ageLabel.text = [NSString stringWithFormat:@"%ld",person.age];
28.UIViewController中关于nib初始化的函数
- - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil;
从这个函数的说明我们可以知道,如果你subclass一个UIViewController,不管有没有使用NIB, [super initWithNibName:bundle]这个方法必须被调用, 这个方法会在如下两种情况下被调用:
- 显示调用, 指定一个nib名称,系统会去找指定的nib
- 在父类的Init方法中被调用,如果这种情况,两个参数都会是nil,系统会去找和你自定以的UIViewController相同名字的nib
如果系统找到nib文件,就会把nib文件中的内容加载进来,
有一点需要解释,initWithNibName:bundle方法并不会加载nib, 当UIViewController的view属性第一次被使用的时候,系统就会调用UIViewController中的loadView方法,在这个方法中会加载nib文件。
如果不用nib,我们可以在loadview中创建view的层次结构,对于有nib的情况,我们也可以在这个方法中做想要的修改。
NSBundle Nib装载方法
29、解决webView的汉字显示问题
- NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://linode-back-cn.b0.upaiyun.com/articles/d34/372/db6edd24d68302930fbc5fd44c.html"]]];
- [self.webView loadData:data MIMEType:@"text/html" textEncodingName:@"UTF-8" baseURL:nil];
1、在appDelegate中加入一个navigation用来控制所有的页面跳转
2、将login页面作为navigation的root view
3、在appDelegate中判断程序是否是第一次登陆,如果是直接进入login页面,如果不是则跳过login页面,push下一个页面(程序主页面,且采用的是tab+nav的结构)
4、程序主页面中对应的每个tab页面都是一个nav的结构
5、当点击注销按钮时,利用appDelegate中的导航将主页面pop出来,此时程序便又重新回到了login页面。
31.Label自适应高度
- UILabel *descLable=[[UILabel alloc] init];
- [descLable setNumberOfLines:0];
- descLable.lineBreakMode = UILineBreakModeCharacterWrap;
- descLable.text = _newsListModel.news_comtent;
- descLable.font = [UIFont systemFontOfSize:12];
- UIFont *font = [UIFont fontWithName:@"Arial" size:12];
- CGSize size = CGSizeMake(300, MAXFLOAT);
- CGSize labelsize = [_newsListModel.news_comtent sizeWithFont:font constrainedToSize:size lineBreakMode:UILineBreakModeCharacterWrap];
- [descLable setFrame:CGRectMake(10, 280,300, labelsize.height)];
- [headView addSubview:descLable];
-
-
- view.backgourd.color = [uicolor colorwithred green blue alpha:0.5]
————————————————————————————————————————————————————————————————————————
32、SDWebImage手动清除缓存的方法
1.找到SDImageCache类
2.添加如下方法:
- - (float)checkTmpSize
- {
- float totalSize = 0;
- NSDirectoryEnumerator *fileEnumerator = [[NSFileManager defaultManager] enumeratorAtPath:diskCachePath];
- for (NSString *fileName in fileEnumerator)
- {
- NSString *filePath = [diskCachePath stringByAppendingPathComponent:fileName];
-
- NSDictionary *attrs = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil];
-
- unsigned long long length = [attrs fileSize];
-
- totalSize += length / 1024.0 / 1024.0;
- }
- // NSLog(@"tmp size is %.2f",totalSize);
-
- return totalSize;
- }
新版的SDImageCache类,已增加此方法
- [[SDImageCache sharedImageCache] getSize];
3.在设置里这样使用
- #pragma 清理缓存图片
-
- - (void)clearTmpPics
- {
- [[SDImageCache sharedImageCache] clearDisk];
-
- // [[SDImageCache sharedImageCache] clearMemory];//可有可无
-
- DLog(@"clear disk");
-
- float tmpSize = [[SDImageCache sharedImageCache] checkTmpSize];
-
- NSString *clearCacheName = tmpSize >= 1 ? [NSString stringWithFormat:@"清理缓存(%.2fM)",tmpSize] : [NSString stringWithFormat:@"清理缓存(%.2fK)",tmpSize * 1024];
-
- [configDataArray replaceObjectAtIndex:2 withObject:clearCacheName];
-
- [configTableView reloadData];
- }
32、第三方MJ使用方法
1、只需修改环境中的footer和base -fobjc-arc
2、选中项目 - Project - Build Settings - ENABLE_STRICT_OBJC_MSGSEND 将其设置为 NO 即可
常用和易错的记录会持续更新..............敬请关注!
转自 http://blog.csdn.net/qq_31810357/article/details/49404345