如何打印 nscharacterset 详解

UDIDIn addition to the serial number, each iOS device has a special 40-character long identification code called UDID. UDID stands for Unique Device Identifier. It looks like this: 3c6f0cc904d137be2e.Developers need to add the UDID to the beta application to be able to install it on your iOS device. Just like people need their ID to board a plane, iOS devices need to have their UDID registered to join the test.总结 - TF_LIU的博客 - CSDN博客
原文地址:/ios/99.html
项目时间紧张了,要自己带孩子了,又有同事离职了,G20来了,写作兴致不高了。。。等等原因,就是不想写点什么,就想躺在沙发上,什么都不想动。今天2个版本终于提交App Store了,突然有好多时间可以挥霍,很是HAPPY。^-^
1.cocoa pods 常用的framework
platform&:ios,&'7.0'
target&'store'&do
pod&'AFNetworking',&'~&&3.1.0'
pod&'JSONKit',&'~&&1.5pre'
pod&'MBProgressHUD',&'~&&0.9.2'
pod&'SDWebImage',&'~&&3.7.6'
pod&'SVPullToRefresh',&'~&&0.4.1'
pod&'JTObjectMapping',&'~&&1.1.2'
pod&'MagicalRecord',&'~&&2.3.2'
pod&'GetuiSDK',&'~&&1.4.2'
pod&'XTSafeCollection',&'~&&1.0.4'
pod&'libWeChatSDK',&'~&&1.6.2'
pod&'XMLDictionary',&'~&&1.4'
pod&'Masonry',&'~&&1.0.0'
pod&'OpenUDID',&'~&&1.0.0'
pod&'SAMKeychain',&'~&&1.5.0'
pod&'iVersion',&'~&&1.11.4'
pod&'iCloudDocumentSync',&'~&&7.4.1'
2.NSInteger打印以及字符串的转换
使用%zd打印NSInteger, %tu打印NSUInteger。
NSInteger&integer&=&1;
NSLog(@&first&number:&%zd&,&integer);
NSUInteger&uinteger&=&1;
NSLog(@&second&number:&%tu&,&uinteger);
3.UIScrollView 在iOS7中使用了Autolayout 导致不能滚动
-&(void)viewDidLayoutSubviews
&&&&&[_mainScrollView&setContentSize:CGSizeMake(SCREEN_WIDTH,&SCREEN_HEIGHT&+&10)];//增加10个像素让scrollview可上下滑动}
添加scrollView的content高度.
4.APP包瘦身
1)删除项目中没有使用的图片。&
2)删除项目中没有用到的class 和 xib 及storyboard。
安装 fui 工具
sudo gem install fui -n /usr/local/bin
fui usage:&/dblock/fui
到工程目录下,执行 fui find 命令,可以找出所有的没有用到的class文件。
3)分析ipa包,找出大于500K的文件或内容 使用
find&.&-type&f&-size&+500000c&|&xargs&ls&-lh
图形搜索法
5.直接iOS7的连续跳转
-&(void)back
&&&&[self&dismissViewControllerAnimated:YES
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&completion:^{&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&if&(self.loginCanceled)&{&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&self.loginCanceled();&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&self.loginCanceled&=&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&}
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&}];
其中loginCanceled的实现
[weakSelf.navigationController&popViewControllerAnimated:YES];
6.去除Preferred Max 的警告
警告的原因:
xib或storyboard中添加了UILabel的控件
UILabel的number lines 大于1
UILabel的preferred max没有设置值(&@property(nonatomic) CGFloat preferredMaxLayoutWidth NS_AVAILABLE_IOS(6_0);)
解决方法:
1)如果是Storyboard的,右键点击警告
2)查看警告的详情
3)复制ID的值在搜索框中进行搜索
4)点击搜索到的Label,可以找到label
5)设置preferred width为0,并选中explicit
6)警告解决
如果警告的是Xib,直接点击警告
就会跳转到对应的UILabel控件,设置preferred width为0,并选中explicit。 警告解决。
7.Cocoa pods更新到1.0 不能用了
更新完cocoa pods后,执行pod install后提示
Errno::ENOTEMPTY - Directory not empty @ dir_s_rmdir - /Users/arthurwang/SVN///*/Pods
[!] Oh no, an error occurred.Search for existing GitHub issues similar to yours:&none
exists, create a ticket, with the template displayed above, on:&sure
to first read the contributing guide for details on how to properly submit a ticket:
Don't forget to anonymize any private data!
解决方法:
删除项目中的Pods文件夹,再进行pod install的安装
8.interactivepopgesturerecognizer 使用
设置left bar button后,会导致右滑返回的效果失效,查看完美的设置方案。
同时为了获取到右滑返回的事件,可以执行
[self.navigationController.interactivePopGestureRecognizer addTarget:self action:@selector(back)];
在ViewController中viewDidAppare中添加,在viewWillDisappear中remove。
9.更新Cocoapods上的代码
1)采用私有的Cocoapods管理代码,需要添加
pod repo add HXSpec git@:ios/HXSpecs.git
将私有的Spec管理Git添加到pod的specs中。为了方便更新私有库。
2)在使用Cocoapods管理代码的时候,如果在GitHut上更新了代码,希望在project中执行pod install 来刷新代码,那么需要删除Pods和Podfile.lock文件
然后在执行pod install 来刷新代码
使用pod update进行repo的更新(更新私有库)
3)多次安装pod install 会出现Build Phase里多个Check Pods Manifest.lock的选项,这些选项可以删除。
采用直接将specs文件放到HXSpecs的管理库中,那么需要执行pod update 进行
Updating local specs repositories
不然会报错
4)删除这个目录下的缓存文件,进行第三方库文件的重新获取
/Users/arthurwang/Library/Caches/CocoaPods/Pods
5)进行两个组件相互依赖的时候,会导致报错:
[!] There is a circular dependency between StoreLocation and StoreBase
10. UICollectionView的数据不够,无法滑动——解决方案
tableView的数据无论多少,它的界面默认都是可以滑动的。
和tableView相比,当collectionView的数据较少不够一个屏幕时,它无法滑动。
解决方案:
_collectionView.alwaysBounceVertical&=&YES;
设置为总能垂直滑动就OK了。
11.MLeaksFinder 检查内存泄露
MLeaksFinder 直接用Pod导入就可以。根据DEBUG这个宏,开启内存泄露的检查,如果发现内存泄露,将断言。 So Good
12.删除String的中文
思路: 采用删除不用需要保留的字符,来实现删除中文的目的
//数字和字母
#define&ALPHANUM&@&ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz&
#define&NUM&@&&
NSCharacterSet&*cs&=&[[NSCharacterSet&characterSetWithCharactersInString:ALPHANUM]&invertedSet];
NSString&*filteredStr&=&[[textStr&componentsSeparatedByCharactersInSet:cs]&componentsJoinedByString:@&&];
另外:UITextField 只能输入数字和字母
[[NSNotificationCenter&defaultCenter]&addObserver:self
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&selector:@selector(textFieldChanged:)
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&name:UITextFieldTextDidChangeNotification
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&object:nil];
监听name:UITextFieldTextDidChangeNotification&和&- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
一起使用,来实现。
-&(BOOL)validatePasswordString:(NSString&*)resultMStr
&&&&BOOL&result&=&YES;
&&&&switch&(self.mode)&{
&&&&&&&&case&HXSChangePasswordLogin:&{
&&&&&&&&&&&&NSString&*regex&=&@&^[a-zA-Z0-9]+$&;
&&&&&&&&&&&&NSPredicate&*pred&=&[NSPredicate&predicateWithFormat:@&SELF&MATCHES&%@&,&regex];
&&&&&&&&&&&&result&=&[pred&evaluateWithObject:resultMStr];
&&&&&&&&&&&&
&&&&&&&&case&HXSChangePasswordPay:&{
&&&&&&&&&&&&NSString&*regex&=&@&^[0-9]+$&;
&&&&&&&&&&&&NSPredicate&*pred&=&[NSPredicate&predicateWithFormat:@&SELF&MATCHES&%@&,&regex];
&&&&&&&&&&&&result&=&[pred&evaluateWithObject:resultMStr];
&&&&&&&&&&&&
&&&&return&
13.iOS8 以后用WKWebView替代UIWebView
iOS8 之前使用UIWebView进行html的展示,使用UIWebView存在内存占用过大并不释放的问题。
WKWebView解决了内存占用过大的问题。
14.Xib中UILabel换行
在Xib中输入很长的文字,需要根据编号进行换行时,按“Enter”键无效。
方法:将文字在Text编辑工具编写好,copy到UILabel上。换行就有了
15.workspace — project — targets 讲解
一个工作空间可以包含多个项目,一个项目可以包含多个目标(生成物)。
一个项目中根据运行的targets不同,可以进行不同的编译设置,project是基础父类,targets是子类,targets的设置会覆盖project的设置。
16.绘画虚线, drawRect绘画frame未定的情况
[yourView.layer&setBorderWidth:5.0];
[yourView.layer&setBorderColor:
[[UIColor&colorWithPatternImage:[UIImage&imageNamed:@&DotedImage.png&]]&CGColor]];//just&add&image&name&and&create&image&with&dashed&or&doted&drawing&and&add&here
这里只需要添加QuartzCore/QuartzCore.h框架,像下面一样导入.m文件:
当使用Autolayout后,绘画虚线是根据frame进行的,那么在
-&(void)drawRect:(CGRect)rect
&&&&[self&drawBorderLayer];
drawRect方法中,进行绘画。
17.Array 的深复制
指针的复制
dataArray3=[dataArray2 mutableCopy];
知识对dataArray2 进行了深复制,数组中的内容仅仅是指针的复制。
单层深复制
dataArray3=[[NSMutableArray alloc]initWithArray:dataArray2 copyItems:YES];
dataArray2进行本身和内容的深复制。单仅仅是内容的第一层
完全深复制
dataArray3 = [NSKeyedUnarchiver unarchiveObjectWithData:[NSKeyedArchiver archivedDataWithRootObject:dataArray2]];
不管多少层都可以进行了深复制
18.企业证书下载版本可在APP中直接打开
在APP中有H5的页面,可以直接点击进行其他应用的下载
19.URL中对“#”的处理
NSString&*str&=&@&/#/dte{}|||?lsfj=12&sdlfj=34&hao=你好&;&&&&&&&
NSURL&*url&=&[NSURL&URLWithString:[str&stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet&characterSetWithCharactersInString:@&`%^{}\&[]|\\&&&&].invertedSet]];
NSLog(@&url&is&%@&,&url);
# 没有被转义
iOS9版本中需要使用&
stringByAddingPercentEncodingWithAllowedCharacters替代之前stringByAddingPercentEscapesUsingEncoding。
NSString&*str&=&@&/#/dte{}|||?lsfj=12&sdlfj=34&hao=你好&;&&&&&&&
NSURL&*url&=&[NSURL&URLWithString:[str&stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSLog(@&[url&scheme]&is&%@.&,&[url&scheme]);
NSLog(@&[url&host]&is&%@.&,&[url&host]);
NSLog(@&[url&password]&is&%@.&,&[url&password]);
NSLog(@&[url&user]&is&%@.&,&[url&user]);
NSLog(@&[url&path]&is&%@.&,&[url&path]);
NSLog(@&[url&query]&is&%@.&,&[url&query]);
NSLog(@&[url&fragment]&is&%@.&,&[url&fragment]);
NSLog(@&[url&resourceSpecifier]&is&%@.&,&[url&resourceSpecifier]);
NSLog(@&[url&parameterString]&is&%@.&,&[url&parameterString]);
NSLog(@&[url&relativePath]&is&%@.&,&[url&relativePath]);
18:57:52.913 store[] [url scheme] is http.
18:57:52.913 store[] [url host] is .
18:57:52.914 store[] [url password] is (null).
18:57:52.914 store[] [url user] is (null).
18:57:52.914 store[] [url path] is /#/dte{}|||.
18:57:52.914 store[] [url query] is lsfj=12&sdlfj=34&hao=%E4%BD%A0%E5%A5%BD.
18:57:52.914 store[] [url fragment] is (null).
18:57:52.915 store[] [url resourceSpecifier] is ///%23/dte%7B%7D%7C%7C%7C?lsfj=12&sdlfj=34&hao=%E4%BD%A0%E5%A5%BD.
18:57:52.915 store[] [url parameterString] is (null).
18:57:52.915 store[] [url relativePath] is /#/dte{}|||.
20.APP 启动页不更新
修改了LaunchScreen.xib 后,模拟器上显示正常,但是真机上没有更新。
原因:&应用缓存
解决:真机上删除APP,重启手机,重新安装APP。
21. httpsdns 使用
申请 account id 下载sdk
查看SDK 文档 初始化,替换域名为IP
/document_detail/30116.html?spm=5176.product.bLXrJ4
在阿里云 里配置域名
22.打印不出变量的值 都显示nil
当对某个变量进行调试的并打印值时,一直返回nil。但是界面又能显示内容。
原因:说明这个变量是在某个线程中,而调试的不在这个线程里。
23.判断是否为gif/png图片的正确姿势
//通过图片Data数据第一个字节&来获取图片扩展名
-&(NSString&*)contentTypeForImageData:(NSData&*)data
&&&&uint8_t&c;
&&&&[data&getBytes:&c&length:1];
&&&&switch&(c)
&&&&&&&&case&0xFF:
&&&&&&&&&&&&return&@&jpeg&;
&&&&&&&&case&0x89:
&&&&&&&&&&&&return&@&png&;
&&&&&&&&case&0x47:
&&&&&&&&&&&&return&@&gif&;
&&&&&&&&case&0x49:
&&&&&&&&case&0x4D:
&&&&&&&&&&&&return&@&tiff&;
&&&&&&&&case&0x52:
&&&&&&&&if&([data&length]&&&12)&{
&&&&&&&&&&&&return&
&&&&&&&&NSString&*testString&=&[[NSString&alloc]&initWithData:[data&subdataWithRange:NSMakeRange(0,&12)]&encoding:NSASCIIStringEncoding];
&&&&&&&&if&([testString&hasPrefix:@&RIFF&]
&&&&&&&&&&&&&&&[testString&hasSuffix:@&WEBP&])
&&&&&&&&&&&&return&@&webp&;
&&&&&&&&return&
&&&&return&
其实图片数据的第一个字节是固定的,一种类型的图片第一个字节就是它的标识, 我们来调用一下这个方法:
//假设这是一个网络获取的URL
NSString&*path&=&@&http://pic.rpgsky.net/images//3508cde5f0decbd6b9a30f1.png&;
NSData&*data&=&[NSData&dataWithContentsOfURL:[NSURL&URLWithString:path]];
//调用获取图片扩展名
NSString&*string&=&[self&contentTypeForImageData:data];
//输出结果为&png
NSLog(@&%@&,string);
24.JSPatch 的convertor 工具使用
@implementation&HXSAdTableViewCell
+&(CGFloat)getCellHeightWithObject:(HXSStoreAppEntryEntity&*)storeAppEntryEntity
&&&&CGFloat&scale&=&[storeAppEntryEntity.imageHeightIntNum&floatValue]/[storeAppEntryEntity.imageWidthIntNum&floatValue];
&&&&return&([UIScreen&mainScreen].bounds.size.width)&/&3&*&scale&+&30;
require('UIScreen');
defineClass('HXSAdTableViewCell',&{}&{
getCellHeightWithObject:&function(storeAppEntryEntity)&{
&&&&var&scale&=&storeAppEntryEntity.imageHeightIntNum().floatValue()&/&storeAppEntryEntity.imageWidthIntNum().floatValue();
&&&&return&(UIScreen.mainScreen().bounds().size().width())&/&3&*&scale&+&30;
有一个BUG:&defineClass('HXSAdTableViewCell', {} {&在{}后面少一个“,”。
require('UIScreen');
defineClass('HXSAdTableViewCell',&{},&{
getCellHeightWithObject:&function(storeAppEntryEntity)&{
&&&&var&scale&=&storeAppEntryEntity.imageHeightIntNum()&/&storeAppEntryEntity.imageWidthIntNum();
&&&&return&(UIScreen.mainScreen().bounds().width)&/&3&*&scale&+&30;
25.Navigation bar的left bar button 跳动
-&(void)jumpToViewController:(UIViewController&*)vc
&&&&//&show&the&navigation&bar&in&other&vcs
&&&&[self.navigationController&setNavigationBarHidden:NO];
&&&&[self.navigationController&pushViewController:vc&animated:YES];
当设置了&self.navigationItem.leftBarButtonItem.imageInsets = self.navigationController.viewControllers.count == 1 ? UIEdgeInsetsZero : UIEdgeInsetsMake(0, -5, 0, 5);
那么进行显示navigation bar的时候,就引起left bar button的跳动。
可以设置navigation bar hidden在push之前来解决。
26.Xcode8 出现ubsystem: com.apple.UIKit, category: HIDEventFiltered。。。的日志
解决办法:【product】-【scheme】-【Edit Scheme】-【Run】-【Argument】-【Environment Variable】添加keyValue【OS_ACTIVITY_MODE disable】可以停止输出打印此日志
27.intrinsic size 同一行有2个可变长度的的UILabel
Content Hugging Priority代表控件拒绝拉伸的优先级。优先级越高,控件会越不容易被拉伸。
而下面的Content Compression Resistance Priority代表控件拒绝压缩内置空间的优先级。优先级越高,控件的内置空间会越不容易被压缩
设置Content Hugging Priority 和 Content Compression Resistance Priority, 可实现当2个UILabel的内容都很长的时候,哪个label进行压缩,哪个Label进行显示完整。
28.pusher 推送测试
/noodlewerk/NWPusher/releases/tag/0.7.0
直接进行推送的测试。
29.float的精度解决
将NSNumber转化为CGFloat时,精度失真。
NSString&*decimalNumberMutiplyWithString(NSString&*multiplierValue,NSString&*multiplicandValue)
&&&&NSDecimalNumber&*multiplierNumber&=&[NSDecimalNumber&decimalNumberWithString:multiplierValue];
&&&&NSDecimalNumber&*multiplicandNumber&=&[NSDecimalNumber&decimalNumberWithString:multiplicandValue];
&&&&NSDecimalNumber&*product&=&[multiplicandNumber&decimalNumberByMultiplyingBy:multiplierNumber];
&&&&return&[product&stringValue];
NSLog(@&%@&,decimalNumberMutiplyWithString([NSString&stringWithFormat:@&%f&,a],&[NSString&stringWithFormat:@&%d&,b]));&//输出结果&
通过计算每一位的数字,再进行string展示。
-&(NSString&*)convertStringFromFloatNum:(NSNumber&*)floatNum
&&&&NSNumberFormatter&*numberFormatter&=&[[NSNumberFormatter&alloc]&init];
&&&&[numberFormatter&setPositiveFormat:@&0.00&];
&&&&NSString&*tempFloatStr&=&[numberFormatter&stringFromNumber:[NSNumber&numberWithDouble:([floatNum&floatValue]&*&100)]];&&//&yuan&to&fen
&&&&NSInteger&tempInt&=&[tempFloatStr&integerValue];
&&&&NSInteger&result&=&tempInt&%&100;
&&&&if&(0&==&result)&{
&&&&&&&&NSString&*str&=&[NSString&stringWithFormat:@&%zd&,&tempInt/100];
&&&&&&&&return&
&&&&result&=&tempInt&%&10;
&&&&if&(0&==&result)&{
&&&&&&&&NSString&*str&=&[NSString&stringWithFormat:@&%zd.%zd&,&tempInt/100,&(tempInt&%&100)/10];
&&&&&&&&return&
&&&&NSString&*str&=&[NSString&stringWithFormat:@&%zd.%zd%zd&,&tempInt/100,&(tempInt&%&100)/10,&(tempInt&%&100)];
&&&&return&
30.个推iOS10改动
iOS 10 中 “loc-key”和“body”(我们官网就是“message”)这二个字段的优先级发生了变化,在iOS 10中“body”的优先级大于“loc-key”,在iOS 10以下“loc-key”大于“body”,不推荐使用“body”传递数据
将Message(对应body)中的数据放到payload中,将loc-key的数据放到message(对应body)中,在iOS 10中就不会出现显示代码了
31.iOS10 默认的frame
32.腾讯手机管家 骚扰拦截 数据库更新失败
骚扰拦截功能,进行数据库更新时,如果是英文环境,一直会出现数据库更新失败,切换到中文环境,一次性就成功了。
我的热门文章1.1.图片灰度图的产生(公式):
单个像素点的rgb值一样:result = red*30%+green*59%+blue*11%
调节亮度就改变该值(result)。
<span style="color:#.2.图片灰度图
-(UIImage*)getGrayImage:(UIImage*)sourceImage&
&&& int width = sourceImage.size.&
&&& int height = sourceImage.size.&
&&& CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();&
&&& CGContextRef context = CGBitmapContextCreate (nil,width,height,8,0,colorSpace,kCGImageAlphaNone);&
&&& CGColorSpaceRelease(colorSpace);&
&&& if (context == NULL) {&
&&& CGContextDrawImage(context,CGRectMake(0, 0, width, height), sourceImage.CGImage);&
&&& UIImage *grayImage = [UIImage imageWithCGImage:CGBitmapContextCreateImage(context)];&
&&& CGContextRelease(context);&
&&& return grayI&
其中,CGColorSpaceCreateDeviceGray会创建一个设备相关的灰度颜色空间的引用
<span style="color:#.3.图片反射度设置(公式):
单个像素点的rgb&#20540;:result = 底图分量(r,g,b)*(1-r)&#43;反射分量(r,g,b)*r;
r为反射度,其&#20540;为(0-1);
调节亮度就改变该&#20540;(result)。
<span style="color:#.根据图片创建位图
- (void) createRGBABitmapContextFromImage:(CGImageRef) inImage withContectRef:(CGContextRef
*)contextRef
{//根据图片大小创建一个位图
CGColorSpaceRef colorS
void *& & & & & bitmapD
int & & & & & & bitmapByteC
int & & & & & & bitmapBytesPerR
size_t pixelsWide =
CGImageGetWidth(inImage);
size_t pixelsHigh =
CGImageGetHeight(inImage);
bitmapBytesPerRow & = (pixelsWide *
bitmapByteCount & & = (bitmapBytesPerRow * pixelsHigh);
colorSpace =
CGColorSpaceCreateDeviceRGB();
if (colorSpace ==
bitmapData =
malloc( bitmapByteCount );
if (bitmapData ==
CGColorSpaceRelease( colorSpace );
*contextRef =
CGBitmapContextCreate (bitmapData,
pixelsWide,
pixelsHigh,
bitmapBytesPerRow,
colorSpace,
kCGImageAlphaPremultipliedLast);
if ((*contextRef) ==
free (bitmapData);
CGColorSpaceRelease( colorSpace );
<span style="color:#.由位图得到图片数据
- (void*)getImageData:(UIImage*)image&
&&&&void* imageD&
&&&&if (imageData == NULL) &
&&&&&&&&imageData = malloc(4 * image.size.width * image.size.height);&
&&&&CGColorSpaceRef cref = CGColorSpaceCreateDeviceRGB();&
&&&&CGContextRef gc = CGBitmapContextCreate(imageData,&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&image.size.width,image.size.height,&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&8,image.size.width*4,&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&cref,kCGImageAlphaPremultipliedFirst);&
&&&&CGColorSpaceRelease(cref);&
&&&&UIGraphicsPushContext(gc);&
&&&&[image drawAtPoint:CGPointMake(0.0f, 0.0f)];&
&&&&UIGraphicsPopContext();&
&&&&CGContextRelease(gc);&
&&&&return imageD&
<span style="color:#.判断touch到子视图或离开视图
- (void)touchesMoved:(NSSet *)touches& withEvent(UIEvent*)event
&&& UITouch *touch=[touches anyObject];
&&& if (![self pointInside:[touch locationInView:self] withEvent:nil])&
&&&&&&& NSLog(@&touches moved outside the view&);
&&&&&&& UIView *hitView=[self hitTest:[[touches anyObject] locationInView:self] withEvent:nil];
&&&&&&& if (hitView==self)
&&&&&&&&&&& NSLog(@&touches moved in the view&);
& & & & else
&&&&&&&&&&& NSLog(@&touches moved in the subview&);
<span style="color:#.判iOS移除全部subview和判断子视图是否加上
NSArray *views = [self subviews];
for(UIVIew* view in views)
&&&&[view removefromsuperview];
判断子视图是否加了
for(UIView *view = self.view.subViews)
if(View isKindOfCless:[OneViewObject class])
BOOL needAddToViewFlag = YES;
for(UIView *view = self.view.subViews)
if(View isKindOfCless:[OneViewObject class])
needAddToViewFlag = NO;
if (needAddToViewFlag)&
[self.view addSubview:someView];
<span style="color:#.软键盘隐藏和移动键盘挡住的视图
方法:在窗口的最底层添加一个*的控件
定义一个方法
移动键盘上面的文本框
& & & 当系统收到显示键盘的请求时,就从屏幕的底部滑出键盘,并将它放在应用程序内容的上方。由于键盘位于您的内容的上面,所以有可能遮掩住用户希望编辑的文本对象。如果这种情况发生,就必须对内容进行调整,使目标对象保持可见。
需要做的调整通常包括暂时调整一或多个视图的尺寸和位置,从而使文本对象可见。管理带有键盘的文本对象的最简单方法是将它们嵌入到一个(或其子类,如)对象。当键盘被显示出来时,您需要做的只是调整滚动视图的尺寸,并将目标文本对象滚动到合适的位置。为此,在通告的处理代码中需要进行如下操作:
[list=1]取得键盘的尺寸。
将滚动视图的高度减去键盘的高度。
将目标文本框滚动到视图中。
图5-6演示了一个简单的应用程序如何处理上述的几个步骤。该程序将几个文本输入框嵌入到UIScrollView对象中,当键盘出现时,通告处理代码首先调整滚动视图的尺寸,然后用UIScrollView类的方法将被触击的文本框滚动到视图中。
图5-6&&调整内容的位置,使其适应键盘
请注意:在配置滚动视图时,请务必为所有的内容视图配置恰当的自动尺寸调整规则。在之前的图中,文本框实际上是一个对象的子视图,该UIView对象又是UIScrollView对象的子视图。如果该UIView对象的和选项被设置了,则改变滚动视图的边框尺寸会同时改变它的边框,因而可能导致不可预料的结果。禁用这些选项可以确保该视图保持尺寸不变,并正确滚动。
程序清单5-1显示了如何注册接收键盘和如何实现相应的处理器方法。这段代码是由负责滚动视图管理的实现的,其中scrollView变量是一个指向滚动视图对象的插座变量。每个处理器方法都从通告的info对象取得键盘的尺寸,并根据这个尺寸调整滚动视图的高度。此外,keyboardWasShown:方法的任务是将当前活动的文本框矩形滚入视图,该文本框对象存储在一个定制变量中(在本例子中名为activeField),该变量是视图控制器的一个成员变量,在委托方法中进行赋&#20540;,委托方法本身的代码显示在中(在这个例子中,视图控制器同时也充当所有文本输入框的委托)。
程序清单5-1&&处理键盘通告
// Call this method somewhere in your viewcontroller setup&code.
- (void)registerForKeyboardNotifications
&&&[[NSNotificationCenter defaultCenter] addObserver:self
&&&&&&&&&&&selector:@selector(keyboardWasShown:)
&&&&&&&&&&&name:UIKeyboardDidShowNotification object:nil];
&&&[[NSNotificationCenter defaultCenter] addObserver:self
&&&&&&&&&&&selector:@selector(keyboardWasHidden:)
&&&&&&&&&&&name:UIKeyboardDidHideNotification object:nil];
// Called when the UIKeyboardDidShowNotificationis sent.
-(void)keyboardWasShown:(NSNotification*)aNotification
&&&if (keyboardShown)
&&&NSDictionary* info = [aNotification userInfo];
&&&// Get the size of the keyboard.
&&&NSValue* aValue = [info objectForKey:UIKeyboardBoundsUserInfoKey];
&&&CGSize keyboardSize = [aValue CGRectValue].
&&&// Resize the scroll&view&(which is the root view of the window)
&&&CGRect viewFrame = [scrollView frame];
&&&viewFrame.size.height -= keyboardSize.
&&&scrollView.frame = viewF
&&&// Scroll the active text field into view.
&&&CGRect textFieldRect = [activeField frame];
&&&[scrollView scrollRectToVisible:textFieldRect animated:YES];
&&&keyboardShown = YES;
// Called when theUIKeyboardDidHideNotification is sent
-(void)keyboardWasHidden:(NSNotification*)aNotification
&&&NSDictionary* info = [aNotification userInfo];
&&&// Get the size of the keyboard.
&&&NSValue* aValue = [info objectForKey:UIKeyboardBoundsUserInfoKey];
&&&CGSize keyboardSize = [aValue CGRectValue].
&&&// Reset the height of the scroll view to its original value
&&&CGRect viewFrame = [scrollView frame];
&&&viewFrame.size.height &#43;= keyboardSize.
&&&scrollView.frame = viewF
&&&keyboardShown = NO;
上面程序清单中的keyboardShown变量是一个布尔&#20540;,用于跟踪键盘是否可见。如果您的用户界面有多个文本输入框,则用户可能触击其中的任意一个进行编辑。发生这种情况时,虽然键盘并不消失,但是每次开始编辑新的文本框时,系统都会产生UIKeyboardDidShowNotification通告。您可以通过跟踪键盘是否确实被隐藏来避免多次减少滚动视图的尺寸。
<span style="color:#.隐藏状态栏
隐藏状态栏:
自动适应父视图大小:
<span style="color:#.释放webview缓存
NSURLCache *sharedCache
= [[NSURLCache alloc] initWithMemoryCapacity:<span style="color:#
diskCapacity:<span style="color:# diskPath:nil];
[NSURLCache setSharedURLCache:sharedCache];
//Clear All Cookies
for(NSHTTPCookie
*cookie in
[[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies])
& & //if([[cookie domain] isEqualToString:someNSStringUrlDomain]) {
& & [[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
<span style="color:#.得到画图所用的时间
- (void)drawRect:(CGRect)rect {
& & if (CGRectEqualToRect(rect, imageRect)) {
& & & & uint64_t start = mach_absolute_time();
& & & & [image drawAtPoint:imagePoint];
& & & & uint64_t drawTime = mach_absolute_time() -
& & & & NSString *text = [[NSString alloc] initWithFormat:@&%ld&, drawTime];
& & & & UILabel *label = (UILabel *)[self viewWithTag:LABEL_TAG];
& & & & label.text =
& & & & [text release];
10.获取当前app的名称和版本号
NSDictionary&*infoDictionary&=&[[NSBundle&mainBundle]&infoDictionary];&&
//&app名称&&
NSString&*name&=&[infoDictionary&objectForKey:@&CFBundleDisplayName&];&&
//&app版本&&
NSString&*version&=&[infoDictionary&objectForKey:@&CFBundleShortVersionString&];&&
//&app&build版本&&
NSString&*build&=&[infoDictionary&objectForKey:@&CFBundleVersion&];&&
UILabel根据text自动调整大小
label.text&=&@&**********&;&&
CGRect&frame&=&label.&&
frame.size.height&=&10000;&&//&设置一个很大的高度&&
label.frame&=&&&
[label&sizeToFit];&&
frame.size.height&=&label.frame.size.&&
label.frame&=&&&
直接拨打有分机号的电话
[[UIApplication&sharedApplication]&openURL:[NSURL&URLWithString:@&tel://,3333&]];
11.将void *转为图片
void *imageData=malloc(320*480*32);&
CGDataProviderRef dataProvider =
CGDataProviderCreateWithCFData((CFMutableDataRef)imageData);
CGImageRef maskingImage =
CGImageMaskCreate(320,480,
32*320, dataProvider,&
NULL, YES);
CGDataProviderRelease(dataProvider);
free(imageData);
12.旋转(镜像)图片
[UIImage imageWithCGImage:(CGImageRef) scale:(CGFloat) orientation:(UIImageOrientation)];
13.动态图片显示
使用UIWebView可以显示.
NSString *html = [NSString stringWithFormat:@&&img src = 'file://%@/test.gif'&&, [[NSBundle mainBundle] bundlePath]];&
14.应用图标右上角的提示小红圈的实现
[[UIApplication sharedApplication]setApplicationIconBadgeNumber:2];
15.一个问题关于清除本地推送数据 local notification
通过服务器推送时,进入游戏, “通知中心”
会清除掉数据。
但是本地推送我通过“通知中心”点进来,“通知中心”中还继续显示N多条信息,有清除方法吗?
[[UIApplication sharedApplication] scheduledLocalNotifications].count
为0 因为都已经推送出去了。
[UIApplication sharedApplication] cancelAllLocalNotifications];
16.local notification在具体时间推送的问题
代码贴上来
& & NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init];
& & NSString *sZer = @&00:00:00&;
& & [timeFormatter setDateFormat:@&HH:mm:ss&];
& & NSDate *zer = [timeFormatter dateFromString:sZer];
& & [[UIApplication sharedApplication] cancelAllLocalNotifications];
& & UILocalNotification *notify = [[UILocalNotification alloc] init];
& & notify.fireDate =
& & notify.alertBody = @&xxxx&;
& & notify.timeZone = [NSTimeZone defaultTimeZone];
& & notify.soundName = UILocalNotificationDefaultSoundN
& & notify.applicationIconBadgeNumber =
& & [[UIApplication sharedApplication] scheduleLocalNotification:notify];
他不能在00:00:00推送
而是直接在程序运行时推送(代码位于viewdidload里面)
程序定义了一个NSTimer
notify.fireDate不是时间,而是距离推送的时间
17.iphone no architectures to compile for (arches = i386,valid_archs = armv6 armv7)错误解决办法
在targets---&Bulid Settings选项下面的Architectures一栏里,在Valid Architectures里加入一项i386,问题解决。
18.UIView背景颜色渐变
CGContextRef bitmapContext = CGBitmapContextCreate(NULL, 320, 480, 8, 4 * 320, CGColorSpaceCreateDeviceRGB(), kCGImageAlphaNoneSkipFirst);
// Draw Gradient Here
CGContextDrawLinearGradient(bitmapContext, myGradient, CGPointMake(0.0f, 0.0f), CGPointMake(320.0f, 480.0f), );
// Create a CGImage from context
CGImageRef cgImage = CGBitmapContextCreateImage(bitmapContext);
// Create a UIImage from CGImage
UIImage *uiImage = [UIImage imageWithCGImage:cgImage];
// Release the CGImage
CGImageRelease(cgImage);
// Release the bitmap context
CGContextRelease(bitmapContext);
// Create the patterned UIColor and set as background color
[targetView setBackgroundColor:[UIColor colorWithPatternImage:image]];
CGFloat colors[] =
&&&&158 / 255.0, 149 / 255.0, 139 / 255.0, 1.00,
&&&&176 / 255.0, 163 / 255.0, 132 / 255.0, 1.00,
&&&&195 / 255.0, 172 / 255.0, 110 / 255.0, 1.00,
&&&&238 / 255.0, 206 / 255.0, 163 / 255.0, 1.00,
&&&&216 / 255.0, 188 / 255.0, 130 / 255.0, 1.00,
&&&&243 / 255.0, 210 / 255.0, 165 / 255.0, 1.00,
&&&&218 / 255.0, 186 / 255.0, 123 / 255.0, 1.00,
&&&&173 / 255.0, 156 / 255.0, 112 / 255.0, 1.00,
&&&&138 / 255.0, 120 / 255.0, 113 / 255.0, 1.00
CGGradientRef gradient = CGGradientCreateWithColorComponents(rgb, colors, NULL, sizeof(colors)/(sizeof(colors[0])*4));(参数一为颜色空间,参数二为cgfloat颜色数组,参数三为各渐变颜色离中心的距离比,其&#20540;为0-1,参数四为有几组颜色(izeof(colors)/(sizeof(colors[0])*4)))
19.让启动界面图停留几秒
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary
*)launchOptions
& & // Override point for customization after application launch.
& & [NSThread
sleepForTimeInterval:1];
& & self.window.rootViewController =
self.viewController;
& & [self.window
makeKeyAndVisible];
& & return
20.如何改变UITabBarController中tabBar和UINavigationController中navigationBar的颜色
21.UILabel自适应里面的文字,自动调整宽度和高度
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0,0,0,0)];这个frame是初设的,没关系,后面还会重新设置其size。
[label setNumberOfLines:0];
NSString *s = @&string......&;
UIFont *font = [UIFont fontWithName:@&Arial& size:12];
CGSize size = CGSizeMake(320,2000);
CGSize labelsize = [s sizeWithFont:font constrainedToSize:size lineBreakMode:UILineBreakModeWordWrap];
[label setFrame:CGRectMake:(0,0, labelsize.width, labelsize.height)];
[self.view addSubView:label];
这样就可以对s赋&#20540;让其自动调整其大小了。
22.NSFileHandle 文件读写类的使用
下面再来看一个读写文件的类,其实它的实现就是调用语言种文件流的操作。通过取得文件流的指针,然后定位指针的位置从而读取出文件中的内容,同样在文件中写入东西也是同样的道理,下面来看一小短代码。
23.获取沙河路径和改变当前路径
1.//参数NSDocumentDirectory要获取那种路径
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];//去处需要的路径
2.//更改到待操作的目录下
[fileManager changeCurrentDirectoryPath:[documentsDirectory stringByExpandingTildeInPath]];
3.如果要指定其他文件目录,比如Caches目录,需要更换目录工厂常量,上面代码其他的可不变:
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSCachesDirectory
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& , NSUserDomainMask
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& , YES);
使用NSSearchPathForDirectoriesInDomains只能定位Caches目录和Documents目录。
4.常用路径工具函数
NSString * NSUserName();
返回当前用户的登录名&
NSString * NSFullUserName();
返回当前用户的完整用户名&
NSString * NSHomeDirectory();
返回当前用户主目录的路径&
NSString * NSHomeDirectoryForUser();
返回用户user的主目录&
NSString * NSTemporaryDirectory();
返回可用于创建临时文件的路径目录&
常用路径工具方法
-(NSString *) pathWithComponents:components &&
根据components(NSArray对象)中元素构造有效路径&
-(NSArray *)pathComponents & & & & & & & & & & & & & & & & & & & & &析构路径,获取路径的各个部分&
-(NSString *)lastPathComponent & & & & & & & & & & & & & & & & & & &
提取路径的最后一个组成部分&
-(NSString *)pathExtension & & & & & & & & & & & & & & & & & & & & &
路径扩展名&
-(NSString *)stringByAppendingPathComponent:path & & & & & & & & & &将path添加到现有路径末尾&
-(NSString *)stringByAppendingPathExtension:ext & & & & &
将拓展名添加的路径最后一个组成部分&
-(NSString *)stringByDeletingPathComponent & & & & & & & & & & & & &
删除路径的最后一个部分&
-(NSString *)stringByDeletingPathExtension & & & & & & & & & & & & &
删除路径的最后一个部分
-(NSString *)stringByExpandingTildeInPath & & & &&
将路径中的代字符扩展成用户主目录(~)或指定用户主目录(~user)&
-(NSString *)stringByResolvingSymlinksInPath & & & & & & & & & & & &
尝试解析路径中的符号链接&
-(NSString *)stringByStandardizingPath & & & & &&
通过尝试解析~、..、.、和符号链接来标准化路径&
使用路径NSPathUtilities.h&
tempdir = NSTemporaryDirectory(); 临时文件的目录名&
path = [fm currentDirectoryPath];
[path lastPathComponent]; 从路径中提取最后一个文件名&
fullpath = [path stringByAppendingPathComponent:fname];将文件名附加到路劲的末尾&
extenson = [fullpath pathExtension]; 路径名的文件扩展名&
homedir = NSHomeDirectory();用户的主目录&
component = [homedir pathComponents]; &路径的每个部分&
NSProcessInfo类:允许你设置或检索正在运行的应用程序的各种类型信息
(NSProcessInfo *)processInfo & & & & & & & & & & & & & & & & &返回当前进程的信息
-(NSArray*)arguments & & & & & & & & & & & & & & & & & & & & &
以NSString对象数字的形式返回当前进程的参数
-(NSDictionary *)environment & & & & & & & & & & & & & & & & &
返回变量/&#20540;对词典。描述当前的环境变量
-(int)processIdentity & & & & & & & & & & & & & & & & & & & & &返回进程标识
-(NSString *)processName & & & & & & & & & & & & & & & & & & &
返回进程名称
-(NSString *)globallyUniqueString &
每次调用该方法都会返回不同的单&#20540;字符串,可以用这个字符串生成单&#20540;临时文件名 &&
-(NSString *)hostname & & & & & & & & & & & & & & & & & & & & &返回主机系统的名称&
-(unsigned int)operatingSystem & & & & & & & & & & & & & & & &
返回表示操作系统的数字&
-(NSString *)operatingSystemName & & & & & & & & & & & & & & & & & &
返回操作系统名称&
-(NSString *)operatingSystemVersionString & & & & & & & & & & & & & & & & & &
返回操作系统当前版本
-(void)setProcessName:(NSString *)name & & & & & & & & &
& & & & & & &将当前进程名称设置为name&
============================================================================
&NSFileHandle类允许更有效地使用文件。
可以实现如下功能:
1、打开一个文件,执行读、写或更新(读写)操作;
2、在文件中查找指定位置;
3、从文件中读取特定数目的字节,或将特定数目的字节写入文件中
另外,NSFileHandle类提供的方法也可以用于各种设备或套接字。
一般而言,我们处理文件时都要经历以下三个步骤:
1、打开文件,获取一个NSFileHandle对象(以便在后面的I/O操作中引用该文件)。
2、对打开文件执行I/O操作。
3、关闭文件。
NSFileHandle*fileHandle
=[[NSFileHandle alloc]init];
fileHandle =[NSFileHandle fileHandleForReadingAtPath:path];//打开一个文件准备读取
fileHandle =[NSFileHandle fileHandleForWritingAtPath:path];
fileHandle =[NSFileHandle fileHandleForUpdatingAtPath:path];
fileData =[fileHandle availableData];//
从设备或者通道返回可用的数据
fileData =[fileHandle readDataToEndOfFile];
[fileHandle writeData:fileData];//将NSData数据写入文件
[fileHandle closeFile];//关闭文件
基本文件操作NSFileHandle
常用NSFileHandle方法
(NSFileHandle *)fileHandleForReadingAtPath:path & & & & & & & & & & & &打开一个文件准备读取
(NSFileHandle *)fileHandleForWritingAtPath:path & & & & & & & & & & & &打开一个文件准备写入
(NSFileHandle *)fileHandleForUpdatingAtPath:path & & & & & & & & & & & &打开一个文件准备更新(读取和写入)
-(NSData *)availableData & & & & & & & & & & & & & & & & & & & & & & & & &从设备或通道返回可用数据
-(NSData *)readDataToEndOfFile & & & & & & & & & & & & & & & & & & & & & &读取其余的数据直到文件末尾(最多UINT_MAX字节)
-(NSData *)readDataOfLength:(unsigned int)bytes
从文件读取指定数目bytes的内容
-(void)writeData:data & & & & & & & & &将data写入文件
-(unsigned long long) offsetInFile & & &获取当前文件的偏移量
-(void)seekToFileOffset:offset & & & &
设置当前文件的偏移量&
-(unsigned long long) seekToEndOfFile & & &将当前文件的偏移量定位的文件末尾
-(void)truncateFileAtOffset:offset & & & &将文件的长度设置为offset字节
-(void)closeFile & & & & & & & & & & & & &
NSString *file1=@&/Users/fhp/Desktop/1.txt&;
*file2=@&/users/fhp/Desktop/2.txt&;
NSFileHandle
*inFile=[NSFileHandle fileHandleForReadingAtPath:file1];
//打开1.txt
if(inFile==nil)
NSLog(@&打开1.txt错误&);
// [[NSFileManager defaultManager] createFileAtPath:file2 contents:nil attributes:nil];
//创建文件 2.txt
NSFileHandle
*outFile=[NSFileHandle fileHandleForWritingAtPath:file2];
[outFile truncateFileAtOffset:0];
//清空内容,把指针指向开头
// [outFile seekToEndOfFile];
//可以把指针移动到文件结尾,这样就是增加文件内容,也可以seekTo到指定的位置
NSMutableData
*buffer=[NSMutableData dataWithCapacity:2048];
((buffer=[inFile readDataOfLength:2048])!=nil)
[outFile writeData:buffer];
//循环读取文件并写入
//当文件不大时,也可以用下面的方法,一次读入整个文件
//最多不超过UINT_MAX个字节,定义在limits.h中,一般为FFFFFFFF,即4GB
// NSData *buffer=[inFile readDataToEndOfFile];
// //读取整个文件内容
// [outFile writeData:buffer];
// //写入文件
[inFile closeFile];
[outFile closeFile];
//关闭文件
注:NSFileHandle类没有提供创建文件的功能,所以必须使用NSFileManager来创建文件。
24.过滤数组中的文件类型和获得文件属性&:
1.&[fileList pathsMatchingExtensions:[NSArrayarrayWithObject:@&jpg&]];
2.NSDictionary * attributes = [filemanager attributesOfItemAtPath:[self getCompletePath] error:nil];
// file size
&&&& NSNumber *theFileS
&&&& if (theFileSize = [attributes objectForKey:NSFileSize])
& & & &_fileSize= [theFileSize intValue];
25.游戏截屏
CCRenderTexture* renderTexture = [CCRenderTexture renderTextureWithWidth:winSize.width height:winSize.height];
&&&&[renderTexture begin];
&&&&[[self parent] visit];
&&&&[renderTexture end];
用这个截屏。用blur模糊。
26.运行无法选择模拟器
& & & & 在targets--》summary--》iOS application target中的devices选项调一下就行(随便调),或者降低一下版本。
27.opencv改变像素点
CvScalar&s;&&&&&&&&&&&&for(int&i&=&0;&i&&&target-&&i&#43;&#43;)&&&&&&&&&&{&&&&&&&&&&&&&&for(int&j&=&0;&j&&&target-&&j&#43;&#43;)&&&&&&&&&&&&&&{&&&&&&&&&&&&&&&&&&s&=&cvGet2D(target,&i,&j);&//&to&get&the&(i,j)&pixel&value&&&&&&&&&&&&&&&&&&if(isNeedFix(s.val[0],&s.val[1],&s.val[2]))&//&to&judge&the&pixel&whether&needs&to&fix&&&&&&&&&&&&&&&&&&&{&&&&&&&&&&&&&&&&&&&&&&changePixelToBlue(s.val[0],&s.val[1],&s.val[2]);&//&fix&pixel&&&&&&&&&&&&&&&&&&&&&&cvSet2D(target,i,j,s);&//&to&reset&the&(i,j)&pixel&value&&&&&&&&&&&&&&&&&&}&&&&&&&&&&&&&&}&&&&&&&&&&}
28.nsvalue使用
将NSRect放入NSArray中
&&&&NSRect rect = NSMakeRect(1, 2, 100, 200);
&&&&NSValue *rectValue = [NSValue valueWithBytes:&rect
&&&&&&&&&&&&&&&&&&&&&&&&objCType:@encode(NSRect)];
&&&&[array addObject:rectValue];
&&&&// 使用getValue提取数&#20540;
&&&&// 传递参数为要存储这个数&#20540;的变量的地址
&&&&rectValue = [array objectAtIndex: 0];
&&&&[rectValue getValue:&rect];NSStringFromCGPoint();& CGPointFromString();
29.viewcontroller剖析
3. 主要属性
控制器管理的根视图
o&title:  控制器导航栏的标题
o&wantsFullScreenLayout: 是否需要全屏显示
o&interfaceOrientation: 界面方向
o&navigationItem: 导航子项
o editing: 是否处理编辑状态
o&hidesBottomBarWhenPushed: 入栈时隐藏底部栏
o&toolbarItems: 工具栏子项集
o&tabBarItem: 标签栏子项
o& editButtonItem:返回一个编辑按钮& &
o&parentViewController&:交视图控制器&
o& &searchDisplayController&:搜索显示控制器
o& &splitViewController&:分割视图控制器
o& modalViewController&:模式控制器
o& navigationController&:导航控制器
o& tabBarController&:标签控制器
4.&主要方法
o&–&loadView:不要主动调用该方法,当访问控制器view的时候,就会调用该方法。如果要自己创建view,则需要重写该方法。
o&–&viewDidLoad:当加载控制器的视图到内存时,该方法被调用。
o& –&viewWillAppear:
o& –&viewDidAppear:
o& –&viewWillDisappear:
o& –&viewDidDisappear:
o&–&shouldAutorotateToInterfaceOrientation:是否支持指定的界面方向。
o&–willAnimateRotationToInterfaceOrientation: duration:将要使用动画过渡到某个界面方向。
o&–&didReceiveMemoryWarning:接收到内存警告信息。
o&–&presentModalViewController:animated:显示模式控制器
o&–&dismissModalViewControllerAnimated:隐藏模式控制器
o&–&setToolbarItems:animated:设置工具栏子项
o&–&setEditing:animated:设置编辑状态
UIView*view = [[UIControl alloc] initWithFrame:CGRectMake(50,200,150,150)] ;
view.backgroundColor = [UIColor clearColor];
[(UIControl *)view addTarget:self action:@selector(xxx) forControlEvents:UIControlEventTouchUpInside];
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@&a.gif&]];
imageView.frame = CGRectMake(0, 0, view.bounds.size.width, view.bounds.size.height);
[view addSubview:imageView];
[imageView release];
[self.view addSubview:view];
[view release];
-(void)viewDidLoad{
UISwipeGestureRecognizer *&
recognizer = [[UISwipeGestureRecognizer
alloc]initWithTarget:self
action:@selector(handleSwipeFrom:)];
&& & [recognizer setDirection:(UISwipeGestureRecognizerDirectionRight)];
& & [[self
view] addGestureRecognizer:recognizer];
[recognizer
& & recognizer = [[UISwipeGestureRecognizer
alloc]initWithTarget:self
action:@selector(handleSwipeFrom:)];
&& & [recognizer setDirection:(UISwipeGestureRecognizerDirectionLeft)];
& & [[self
view] addGestureRecognizer:recognizer];
[recognizer
recognizer = [[UISwipeGestureRecognizer
alloc]initWithTarget:self
action:@selector(handleSwipeFrom:)];
&& & [recognizer setDirection:(UISwipeGestureRecognizerDirectionUp)];
& & [[self
view] addGestureRecognizer:recognizer];
[recognizer
UISwipeGestureRecognizer *
& & recognizer = [[UISwipeGestureRecognizer
alloc]initWithTarget:self
action:@selector(handleSwipeFrom:)];
&& & [recognizer setDirection:(UISwipeGestureRecognizerDirectionDown)];
& & [[self
view] addGestureRecognizer:recognizer];
[recognizer
-(void)handleSwipeFrom:(UISwipeGestureRecognizer *)recognizer{
if(recognizer.direction==UISwipeGestureRecognizerDirectionDown) {
&& & & NSLog(@&swipe down&);
//执行程序
if(recognizer.direction==UISwipeGestureRecognizerDirectionUp) {
&& & & NSLog(@&swipe up&);
//执行程序
if(recognizer.direction==UISwipeGestureRecognizerDirectionLeft) {
&& & & NSLog(@&swipe left&);
//执行程序
if(recognizer.direction==UISwipeGestureRecognizerDirectionRight) {
&& & & NSLog(@&swipe right&);
//执行程序
UIPasteboard *pasteboard = [UIPasteboard
generalPasteboard];
& & pasteboard.string =
self.label.text;
导入MessageUI.framework
.h文件中#import
&MessageUI/MessageUI.h&
#import&MessageUI/MFMailComposeViewController.h&
实现 MFMailComposeViewControllerDelegate,&
MFMessageComposeViewControllerDelegate
-(void)showMailPicker {
& &Class mailClass = (NSClassFromString(@&MFMailComposeViewController&));
if (mailClass !=nil) {
if ([mailClass canSendMail]) {
[selfdisplayMailComposerSheet];
& & & & & &
UIAlertView *alert=[[UIAlertView
alloc] initWithTitle:@&&message:@&设备不支持邮件功能&
delegate:selfcancelButtonTitle:@&确定& otherButtonTitles:nil];
& & & & & & [alert
& & & & & & [alert
& & }else{
-(void)displayMailComposerSheet&
MFMailComposeViewController *picker = [[MFMailComposeViewControlleralloc]
picker.mailComposeDelegate =self;
[pickersetSubject:@&文件分享&];
// Set up recipients
NSArray *toRecipients = [NSArrayarrayWithObject:@&&];&
NSArray *ccRecipients = [NSArrayarrayWithObjects:@&&,@&&,
NSArray *bccRecipients = [NSArrayarrayWithObject:@&&];&
[pickersetToRecipients:toRecipients];
[pickersetCcRecipients:ccRecipients];
[pickersetBccRecipients:bccRecipients];
//发送图片附件
//NSString *path = [[NSBundle mainBundle] pathForResource:@&rainy& ofType:@&jpg&];
//NSData *myData = [NSData dataWithContentsOfFile:path];
//[picker addAttachmentData:myData mimeType:@&image/jpeg& fileName:@&rainy.jpg&];
//发送txt文本附件
//NSString *path = [[NSBundle mainBundle] pathForResource:@&MyText& ofType:@&txt&];
//NSData *myData = [NSData dataWithContentsOfFile:path];
//[picker addAttachmentData:myData mimeType:@&text/txt& fileName:@&MyText.txt&];
//发送doc文本附件&
//NSString *path = [[NSBundle mainBundle] pathForResource:@&MyText& ofType:@&doc&];
//NSData *myData = [NSData dataWithContentsOfFile:path];
//[picker addAttachmentData:myData mimeType:@&text/doc& fileName:@&MyText.doc&];
//发送pdf文档附件
NSString *path = [[NSBundlemainBundle]
pathForResource:@&CodeSigningGuide&ofType:@&pdf&];
NSData *myData = [NSDatadataWithContentsOfFile:path];
[pickeraddAttachmentData:myData
mimeType:@&file/pdf&fileName:@&rainy.pdf&];
// Fill out the email body text
NSString *emailBody =[NSStringstringWithFormat:@&我分享了文件给您,地址是%@&,address]
[pickersetMessageBody:emailBody
isHTML:NO];
[selfpresentModalViewController:picker
animated:YES];
[pickerrelease];
- (void)mailComposeController:(MFMailComposeViewController*)controller&
& & & & & didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
// Notifies users about errors associated with the interface
switch (result)
caseMFMailComposeResultCancelled:
NSLog(@&Result: Mail sending canceled&);
caseMFMailComposeResultSaved:
& & & & & &NSLog(@&Result: Mail saved&);
caseMFMailComposeResultSent:
NSLog(@&Result: Mail sent&);
caseMFMailComposeResultFailed:
NSLog(@&Result: Mail sending failed&);
NSLog(@&Result: Mail not sent&);
[selfdismissModalViewControllerAnimated:YES];
-(void)showSMSPicker{
& &Class messageClass = (NSClassFromString(@&MFMessageComposeViewController&));
if (messageClass != nil) {&
& &// Check whether the current device is configured for sending SMS messages
if ([messageClass canSendText]) {
& & & & [selfdisplaySMSComposerSheet];
& & & & & &
UIAlertView *alert=[[UIAlertView
alloc] initWithTitle:@&&message:@&设备不支持短信功能&
delegate:selfcancelButtonTitle:@&确定& otherButtonTitles:nil];
& & & & & & [alert
& & & & & & [alert
&& & & & & &
-(void)displaySMSComposerSheet
& &MFMessageComposeViewController *picker = [[MFMessageComposeViewControlleralloc]
picker.messageComposeDelegate =self;
NSString *smsBody =[NSStringstringWithFormat:@&我分享了文件给您,地址是%@&,address]
& & picker.body=smsB
[selfpresentModalViewController:picker
animated:YES];
[pickerrelease];
-(void)setRefreshWindow{
CGRect frame = CGRectMake(0.0,
0.0, 320.0,
statusbarWindow = [[UIWindow
alloc] initWithFrame:frame];
& & [statusbarWindow
setBackgroundColor:[UIColor
clearColor]];
& & [statusbarWindow
setWindowLevel:UIWindowLevelStatusBar&#43;1.0f];
添加自定义子视图
UIImageView *customView = [[UIImageView
alloc] initWithFrame:CGRectMake(100,
& & customView.image=[UIImage
imageNamed:@&数据刷新栏.png&];
//& & UILabel *label=[[UILabel alloc] initWithFrame:CGRectMake(100, 0, 100, 20)];
//& & //& & label.backgroundColor=[UIColor clearColor];
//& & label.text=@&数据正在刷新&;
//& & [customView addSubview:label];
& & [statusbarWindow
addSubview:customView];
& & [statusbarWindow
makeKeyAndVisible];
#import &AssetsLibrary/AssetsLibrary.h&
-(void)getImgs{
& & dispatch_async(dispatch_get_main_queue(), ^{
& & & & NSAutoreleasePool *pool = [[NSAutoreleasePool
& & & & ALAssetsLibraryAccessFailureBlock failureblock = ^(NSError *myerror){
& & & & & &
NSLog(@&相册访问失败 =%@&, [myerror
localizedDescription]);
& & & & & &
if ([myerror.localizedDescription
rangeOfString:@&Global denied access&].location!=NSNotFound) {
& & & & & & & & & NSLog(@&无法访问相册.请在'设置-&定位服务'设置为打开状态.&);
& & & & & & }else{
& & & & & & & & NSLog(@&相册访问失败.&);
& & & & & & }
& & & & };
ALAssetsGroupEnumerationResultsBlock groupEnumerAtion = ^(ALAsset *result,
NSUInteger index,
BOOL *stop){
& & & & & &
if (result!=NULL) {
& & & & & & & &
if ([[result valueForProperty:ALAssetPropertyType]
isEqualToString:ALAssetTypePhoto]) {
&& & & & & & & & & &
& & & & & & & & & &
NSString *urlstr=[NSString
stringWithFormat:@&%@&,result.defaultRepresentation.url];//图片的url
/*result.defaultRepresentation.fullScreenImage//图片的大图
result.thumbnail & & & & & & & & & & & & & &
//图片的缩略图小图
//& & & & & & & & & & NSRange range1=[urlstr rangeOfString:@&id=&];
//& & & & & & & & & & NSString *resultName=[urlstr substringFromIndex:range1.location&#43;3];
//& & & & & & & & & & resultName=[resultName stringByReplacingOccurrencesOfString:@&&ext=& withString:@&.&];//&#26684;式demo123456.png
&& & & & & & & & & &
& & & & & & & & & [self._dataArray addObject:urlstr];
& & & & & & & & }
& & & & & & }
& & & & & &
& & & & };
& & & & ALAssetsLibraryGroupsEnumerationResultsBlock
& & & & libraryGroupsEnumeration = ^(ALAssetsGroup* group,
BOOL* stop){
&& & & & & &
& & & & & &
if (group == nil)&
& & & & & & {
&& & & & & & & &
& & & & & & }
&& & & & & &
& & & & & &
if (group!=nil) {
& & & & & & & &
NSString *g=[NSString
stringWithFormat:@&%@&,group];//获取相簿的组
& & & & & & & & NSLog(@&gg:%@&,g);gg:ALAssetsGroup
- Name:Camera Roll, Type:Saved Photos, Assets count:71
& & & & & & & &
NSString *g1=[g substringFromIndex:16 ] ;
& & & & & & & &
NSArray *arr=[[NSArray
alloc] init];
& & & & & & & & arr=[g1
componentsSeparatedByString:@&,&];
& & & & & & & &
NSString *g2=[[arr objectAtIndex:0]
substringFromIndex:5];
& & & & & & & &
if ([g2 isEqualToString:@&Camera Roll&]) {
& & & & & & & & & & g2=@&相机胶卷&;
& & & & & & & & }
& & & & & & & &
NSString *groupName=g2;//组的name
&& & & & & & & &
& & & & & & & & [group
enumerateAssetsUsingBlock:groupEnumerAtion];
& & & & & & }
&& & & & & &
& & & & };
& & & & ALAssetsLibrary* library = [[ALAssetsLibrary
& & & & [library enumerateGroupsWithTypes:ALAssetsGroupAll
&& & & & & & & & & & & & & & &
usingBlock:libraryGroupsEnumeration&
&& & & & & & & & & & & & & &
failureBlock:failureblock];
& & & & [library
release]; & & &
& & & & [pool
//------------------------根据图片的url反取图片-----
& ALAssetsLibrary *assetLibrary=[[ALAssetsLibrary
NSURL *url=[NSURL
URLWithString:urlStr];
[assetLibrary
assetForURL:url resultBlock:^(ALAsset *asset)& {
& & & & & & & &
UIImage *image=[UIImage
imageWithCGImage:asset.thumbnail];
& & & & & & & & cellImageView.image=
& & & & & &
& & & & & & & & }failureBlock:^(NSError *error) {
& & & & & & & & & &
NSLog(@&error=%@&,error);
& & & & & & }
&& & & & & & ];
-(UIView *)findView:(UIView *)aView withName:(NSString *)name{ &
Class cl = [aView class]; &
NSString *desc = [cl description]; &
if ([name isEqualToString:desc]) &
return aV &
for (NSUInteger i =
0; i & [aView.subviews
count]; i&#43;&#43;) &
UIView *subView = [aView.subviews
objectAtIndex:i]; &
& & & & subView = [self
findView:subView withName:name]; &
if (subView) &
& & & & & &
return subV &
& & return
-(void)addSomeElements:(UIViewController *)viewController{
UIView *PLCameraView=[self
findView:viewController.view
withName:@&PLCameraView&];
UIView *bottomBar=[self
findView:PLCameraView withName:@&PLCropOverlayBottomBar&];
UIImageView *bottomBarImageForSave = [bottomBar.subviews
objectAtIndex:0];
UIButton *retakeButton=[bottomBarImageForSave.subviews
objectAtIndex:0]; &
& & [retakeButton setTitle:@&重拍&
forState:UIControlStateNormal];&
//左下角按钮
UIButton *useButton=[bottomBarImageForSave.subviews
objectAtIndex:1]; &
& & [useButton setTitle:@&上传&
forState:UIControlStateNormal];&
//右下角按钮
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController
*)viewController animated:(BOOL)animated{
addSomeElements:viewController];
&NSCharacterSet *whitespace = [NSCharacterSet
whitespaceAndNewlineCharacterSet];
&&NSString * stringStr = [self.titleField.text
stringByTrimmingCharactersInSet:whitespace];
- (void) hideTabBar:(BOOL) hidden{
& & [UIView
beginAnimations:nil
context:NULL];
& & [UIView
setAnimationDuration:0];
for(UIView *view
in&self.tabBarController.view.subviews)
if([view isKindOfClass:[UITabBar
& & & & & &
if (hidden) {
& & & & & & & & [view
setFrame:CGRectMake(view.frame.origin.x,
460, view.frame.size.width, view.frame.size.height)];
& & & & & & }
& & & & & & & & [view
setFrame:CGRectMake(view.frame.origin.x,
460-49, view.frame.size.width, view.frame.size.height)];
& & & & & & }
& & & & }&
& & & & & &
if (hidden) {
& & & & & & & & [view
setFrame:CGRectMake(view.frame.origin.x, view.frame.origin.y,
view.frame.size.width,
& & & & & & }
& & & & & & & & [view
setFrame:CGRectMake(view.frame.origin.x, view.frame.origin.y,
view.frame.size.width,
& & & & & & }
& & [UIView
commitAnimations];
&NSDate *date = [NSDate
& & NSTimeZone *zone = [NSTimeZone
systemTimeZone];
NSInteger interval = [zone secondsFromGMTForDate: date];
NSDate *localeDate = [date& dateByAddingTimeInterval: interval];
&UIImageView *fieldImage=[[UIImageView
alloc]initWithFrame:CGRectMake(37,
48&#43;35,
& & fieldImage.userInteractionEnabled=YES;
fieldImage.contentStretch=CGRectMake(0,
& & fieldImage.image=[UIImage
imageNamed:@&输入框&];
& & [self.view
addSubview:fieldImage];
30.常量的定义,c,obj-c中是外连接的,c&#43;&#43;中是内连接的。
Objective-C是标准C的另一种扩展,那么我犯的错误也就很明显了——当多个编译单元都引用那个define.h文件时出现了重复定义错。
&& &今天来到机房一试,果然如此,只要将
&& &const int NUMOFGHOST = 4;
&& &static const int NUMOFGHOST = 4;
就顺利编译通过了。这里的static是用来把定义的const常量标记为对外不可见的。
&& &这里顺便抱怨一句:这xcode也太不人性化了,重复定义就说重复定义嘛,非要用红红的字标出来&Command /Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/gcc-4.2 failed with exit code 1&,反倒是很重要的那句&ld:
duplicate symbol _NUMOFGHOST in /Users/asfgasiyf/Desktop/pacMan/build/pacMan.build/Debug-iphonesimulator/pacMan.build/Objects-normal/i386/MazeView.o and /Users/asfgasiyf/Desktop/pacMan/build/pacMan.build/Debug-iphonesimulator/pacMan.build/Objects-normal/i386/pacManAppDelegate.o&用灰灰的颜色显示,也不懂得突出一下重点……
31.查看文件是什么框架的
&lipo -info /path/to/your/library.a
32.改变alertview的高度
- (void)willPresentAlertView:(UIAlertView *)openURLAlert
&& // [openURLAlert setFrame:CGRectMake( 300, 100, 300, 300 )];
&&&&[openURLAlert setBounds:CGRectMake(-10, -80, 300, 300 )];
33.显示本地html文件
34.双击手势取消单击手势
[singleOne requireGestureRecognizerToFail:doubleOne];
//防止:双击被单击拦截
35.获得系统语言
21:18 19人阅读
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];&
NSArray *languages = [defaults objectForKey:@&AppleLanguages&];&
NSString *currentLanguage = [languages objectAtIndex:0];
取得设置好的语言。。日语是ja,中文是zh_Hans
NSString *currentLanuage=[[NSLocale currentLocale] objectForKey:NSLocaleLanguageCode];
36.获得设备方向
10:48 220人阅读
& &&//获得设备方向
& &UIInterfaceOrientation orientation = [[UIApplicationsharedApplication]statusBarOrientation];
& & //程序启动时获取当前驱动的方向的方法
& & [[UIDevicecurrentDevice]beginGeneratingDeviceOrientationNotifications];
UIDeviceOrientation currentOrientation = [ [UIDevicecurrentDevice]orientation];
& & //currentOrientation
可以获得UIDevice
& & [[UIDevicecurrentDevice]endGeneratingDeviceOrientationNotifications];
37.去掉应用图标的高亮效果
1.内图标上部高亮效果的办法:
& & 苹果默认会在 App Store
里的应用图标上半部自动添加高亮特效(如下图),虽是好心但有时候这半个光圈会破坏图标设计者的原作。如果您要去掉这一高亮特效,可以在程序的 info.plist
里添加一个&#20540;类型为 boolean 的字段:UIPrerenderedIcon,然后选中。
& & 再上传应用,App Store
就不会在图标上添加高亮特效了。
iphone应用发布:如何去掉应用图标的高亮效果。
2.这需要在info.plist里面设置,Icon&already&includes&gloss&effects,Boolean类型,YES即可
38.实现震动效果
#import &AudioToolbox/AudioToolbox.h&
之后在方法里添加
AudioServicesPlaySystemSound (kSystemSoundID_Vibrate);就可以了
39.检查邮箱的正确性和是否为纯数字
&#43;&(BOOL)validateEmail:(NSString&*)str2validate&&
{&&&&&&NSString&*emailRegex&=&@&[A-Za-z0-9._%&#43;-]&#43;@[A-Za-z0-9.-]&#43;\\.[A-Za-z]{2,4}&;&&
&&&&NSPredicate&*emailPredicate&=&[NSPredicatepredicateWithFormat:@&SELF&MATCHES&%@&,&emailRegex];&&&&&&&&
&&&&return&[emailPredicate&evaluateWithObject:str2validate];&&}&
&#43;&(BOOL)validateNumeric:(NSString&*)str2validate&&{&&
&&&&NSCharacterSet&*charSet&=&[[NSCharacterSet&characterSetWithCharactersInString:@&&]&invertedSet];&&&&&&NSRange&range&=&[str2validate&rangeOfCharacterFromSet:charSet];&&
&&&&return&(range.location&==&NSNotFound)&?&YES&:&NO;&&}&
40.textField的抖动
//TextField的晃动:Begin&&
@interface&UITextField(shake)&&&&
-&(void)&&&&
@implementation&UITextField(shake)&&&&
-&(void)shake&&{&&
&&&&CAKeyframeAnimation&*animationKey&=&[CAKeyframeAnimationanimationWithKeyPath:@&position&];&&&&&&[animationKey&setDuration:0.5f];&&
&&&&&&&&&&NSArray&*array&=&[[NSArrayalloc]&initWithObjects:&&
&&&&&&&&&&&&&&&&&&&&&&[NSValuevalueWithCGPoint:CGPointMake(self.center.x,&self.center.y)],&&&&&&&&&&&&&&&&&&&&&&&&[NSValuevalueWithCGPoint:CGPointMake(self.center.x-5,&self.center.y)],&&
&&&&&&&&&&&&&&&&&&&&&&[NSValuevalueWithCGPoint:CGPointMake(self.center.x&#43;5,&self.center.y)],&&&&&&&&&&&&&&&&&&&&&&&&[NSValuevalueWithCGPoint:CGPointMake(self.center.x,&self.center.y)],&&
&&&&&&&&&&&&&&&&&&&&&&[NSValuevalueWithCGPoint:CGPointMake(self.center.x-5,&self.center.y)],&&&&&&&&&&&&&&&&&&&&&&&&[NSValuevalueWithCGPoint:CGPointMake(self.center.x&#43;5,&self.center.y)],&&
&&&&&&&&&&&&&&&&&&&&&&[NSValuevalueWithCGPoint:CGPointMake(self.center.x,&self.center.y)],&&&&&&&&&&&&&&&&&&&&&&&&[NSValuevalueWithCGPoint:CGPointMake(self.center.x-5,&self.center.y)],&&
&&&&&&&&&&&&&&&&&&&&&&[NSValuevalueWithCGPoint:CGPointMake(self.center.x&#43;5,&self.center.y)],&&&&&&&&&&&&&&&&&&&&&&&&[NSValuevalueWithCGPoint:CGPointMake(self.center.x,&self.center.y)],&&
&&&&&&&&&&&&&&&&&&&&&&nil];&&&&&&[animationKey&setValues:array];&&
&&&&[array&release];&&&&&&&&
&&&&NSArray&*times&=&[[NSArrayalloc]&initWithObjects:&&&&&&&&&&&&&&&&&&&&&&&&[NSNumbernumberWithFloat:0.1f],&&
&&&&&&&&&&&&&&&&&&&&&&[NSNumbernumberWithFloat:0.2f],&&&&&&&&&&&&&&&&&&&&&&&&[NSNumbernumberWithFloat:0.3f],&&
&&&&&&&&&&&&&&&&&&&&&&[NSNumbernumberWithFloat:0.4f],&&&&&&&&&&&&&&&&&&&&&&&&[NSNumbernumberWithFloat:0.5f],&&
&&&&&&&&&&&&&&&&&&&&&&[NSNumbernumberWithFloat:0.6f],&&&&&&&&&&&&&&&&&&&&&&&&[NSNumbernumberWithFloat:0.7f],&&
&&&&&&&&&&&&&&&&&&&&&&[NSNumbernumberWithFloat:0.8f],&&&&&&&&&&&&&&&&&&&&&&&&[NSNumbernumberWithFloat:0.9f],&&
&&&&&&&&&&&&&&&&&&&&&&[NSNumbernumberWithFloat:1.0f],&&&&&&&&&&&&&&&&&&&&&&&&nil];&&
&&&&[animationKey&setKeyTimes:times];&&&&&&[times&release];&&
&&&&&&&&&&[self.layeraddAnimation:animationKey&forKey:@&TextFieldShake&];&&
@end&&//TextField的晃动:End&&
41.UIButton去除按下时的状态
btn2.adjustsImageWhenHighlighted&=&NO;&
42.获得设备的电量
[[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];
if ([[UIDevice currentDevice] batteryState] == UIDeviceBatteryStateCharging) {
& & NSLog(@&Device is charging.&);
43.退出程序
- (void) animationFinished:(NSString *)animationID finished:(NSNumber *)finished
context:(void *)context
if ([animationID
compare:@&exitApplication&] ==
- (void) exitApplication
& & UIWindow *window = [[UIApplication
sharedApplication] keyWindow];
& & [UIView
beginAnimations:@&exitApplication&
context:nil];
setAnimationDuration:0.75];
setAnimationDelegate:self];
setAnimationTransition:UIViewAnimationTransitionCurlDown
forView:window cache:NO];
setAnimationDidStopSelector:@selector(animationFinished: finished: context:)];
& & window.bounds =
CGRectMake(512,
commitAnimations];
//设置画笔线条粗细&&CGContextSetLineWidth(context,&1.0);&&
//设置矩形填充颜色:红色&&CGContextSetRGBFillColor&(context,&1.0,&0.0,&0.0,&1.0);&&
//设置字体&&UIFont&*font&=&[UIFont&boldSystemFontOfSize:31.0];&&
//在指定的矩形区域内画文字&&[text&drawInRect:rect&withFont:font];
45.itunes图标
要加itunes图标就把图标去掉扩展名,改名为iTunesArtwork扔到资源目录下
46.两个应用之间传递信息
在目标程序(通过订制的url开打的程序)中,设置订制的url,订制方法如下:
打开plist文件添加一个键&#20540;对URL types,并设置成如下形式:
其中图中的JJMFAPP就是你自己定义的url协议(名字随别取,最好和应用程序有关联的名字,之后将会用到它)
在其它的应用中打开第一步中的应用,如下:(看见&JJMFAPP:&没,这个就是第一步设置的url协议)
NSURL *jjmfURL = [NSURL
URLWithString:@&JJMFAPP:&];
& & if ([[UIApplication
sharedApplication] canOpenURL:jjmfURL])
& & & & [[UIApplication
sharedApplication] openURL:jjmfURL];
如果要传递参数则如下:(规则是 开头必须是订制的url协议如:JJMFAPP:,随后跟参数,参数之间用&隔开)
& & & & NSString *dataToPath = [NSHomeDirectory()
stringByAppendingPathComponent:@&Documents&];
int updataID = [usersDefault
integerForKey:@&JJMFAPP&];
NSString *informationString = [NSString
stringWithFormat:@&JJMFAPP:message=%@&updataID=%d&,dataToPath,updataID];
& & & & informationString = [informationString
stringByReplacingOccurrencesOfString:@& &
withString:@&%20&];
NSURL *updataURL = [NSURL
URLWithString:informationString];
//& & & & NSLog(@&%@&,updataURL);
if ([[UIApplication
sharedApplication]
canOpenURL:updataURL])
& & & & & & [[UIApplication
sharedApplication]
openURL:updataURL];
在目标程序中解析订制的url并打开程序(必须实现UIApplicationDelegate协议,并实现
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
方法),如下:
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
if (url == nil)
return NO;
NSString *URLString = [url
absoluteString];
if (![URLString hasPrefix:@&JJMFAPP:&])
return NO;
//& & URLString = [URLString substringFromIndex:[URLString rangeOfString:@&UPDATAJJMF:message=&].location&#43;19];
& & & & NSMutableCharacterSet *set = [[NSMutableCharacterSet
& & & & [set addCharactersInString:@&&=&];
NSArray *pathArray = [URLString
componentsSeparatedByCharactersInSet:set];
& & & & [set
& & & & URLString = [pathArray
objectAtIndex:1];
& & & & Arguments2App *arg2app = [Arguments2App
sharedArguments];
& & & & arg2app.groupid = [[pathArray
objectAtIndex:3]
intValue];
& & & & [arg2app
writeToUserDefaults];
& & URLString = [URLString stringByReplacingOccurrencesOfString:@&%20&
withString:@& &];
BOOL pathE
BOOL yes = [[NSFileManager
defaultManager] fileExistsAtPath:URLString
isDirectory:&pathExists];
if (yes && pathExists)
self.viewController.upToPath = URLS
NSUserDefaults *usersDefault = [NSUserDefaults
standardUserDefaults];
& & & & [usersDefault
setObject:URLString
forKey:@&UPDATATOPATH&];
& & & & [usersDefault
synchronize];
self.viewController.upToPath =
& & return
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
此方法中也可以得到订制的url信息
& & {//处理应用程序间信息共享
& & & & NSString *sourceApp = [launchOptions
objectForKey:UIApplicationLaunchOptionsSourceApplicationKey];
& & & & NSURL *url = [launchOptions
objectForKey:UIApplicationLaunchOptionsURLKey];
NSString *msg = [NSString
stringWithFormat:@&sourceApp:%@,url:%@&,sourceApp, url];
UIAlertView *alert = [[UIAlertView
& & & & & & & & & & & & & & &
initWithTitle:NSLocalizedString(@&test message&,
& & & & & & & & & & & & & & &
message:msg
& & & & & & & & & & & & & & &
delegate:self&
& & & & & & & & & & & & & & &
cancelButtonTitle:nil
otherButtonTitles:@&OK&,
& & & & [alert
show];& & &
& & & & [alert
47.icon总结
Icon-72.png
Icon-Small-50.png
Icon-Small.png
Icon-Small@2x.png
Icon@2x.png
iTunesArtwork
Default.png
Default@2x.png
Default-Portrait.png
Default-Landscape.png
48.将秒(UNIX时间截)转为标准时间:时间截的长度不能超过10位,应该是除以取余
简单的来说“”表示从日0点0分0秒到现在为止经过了秒
-(NSString *)dateInFormat:(time_t)dateTime format:(NSString*) stringFormat
& & char buffer[80];
& & const char *format = [stringFormat UTF8String];
& & struct tm *
& & timeinfo = localtime(&dateTime);
& & strftime(buffer, 80, format, timeinfo);
& & return [NSString& stringWithCString:buffer encoding:NSUTF8StringEncoding];
&//NSString& *str = @&%d.%m.%Y %H:%M:%S&;
&NSString& *str = @&%Y-%m-%d %H:%M:%S&;
&NSString& *time = [self dateInFormat:3 format:str];
&NSLog(@&createdAt: %@&,time);
49.数组排序
1.第一种方法
NSSortDescriptor *
switch (segment.selectedSegmentIndex)
sorts = [[NSSortDescriptor
alloc] initWithKey:
@&subject&
ascending: YES];
sorts = [[NSSortDescriptor
alloc] initWithKey:
@&priority&
ascending: YES];
sorts = [[NSSortDescriptor
alloc] initWithKey:
ascending: YES];
NSArray *arr = [NSArray
arrayWithObject: sorts];
& & [tododb.todolist.todoarray
sortUsingDescriptors: arr];
2.第二种方法
//字典的keys数组,按从小到大的顺序排列
& & keysArray = [[[productDic
allKeys] sortedArrayUsingComparator:^(id obj1,
if ([obj1 integerValue] & [obj2
integerValue])
& & & & & & return (NSComparisonResult)NSOrderedDescending;
if ([obj1 integerValue] & [obj2
integerValue])
& & & & & & return (NSComparisonResult)NSOrderedAscending;
& & & & return (NSComparisonResult)NSOrderedSame;
50.日期装换成字符串
NSDateFormatter *dateFormatter = [[NSDateFormatter
alloc] init];
& & NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@&zh_CN&];
& & [dateFormatter setLocale:locale];//location设置为中国
& & [locale release];
& & [dateFormatter setDateFormat:@&yyyy-MM-dd HH:mm:ss EEEE&];
& & todayDate = [NSDate date];
& & dateLabel.text = [dateFormatter stringFromDate:todayDate];
51.摆动动画
//添加登陆界面
- (void)addLandingView
{//添加登陆界面
& & matView = [[UIView
alloc] initWithFrame:CGRectMake(0, 0, )];
& & matView.backgroundColor = [UIColor
clearColor];
& & [self.view
addSubview:matView];
& & [matView
& & JJMFLandingView *landingView = [[JJMFLandingView
alloc] initWithFrame:CGRectMake(0, 0, 500, 240)];
& & landingView.center =
CGPointMake(512, 274);
& & landingView.deleget =
& & [self.view
addSubview:landingView];
& & [landingView
& & CAKeyframeAnimation *animationKey = [CAKeyframeAnimation
animationWithKeyPath:@&position&];
& & [animationKey
setDuration:1.f];
& & NSArray *array = [[NSArray
alloc] initWithObjects:
& & & & & & & & & & & [NSValue
valueWithCGPoint:CGPointMake(512, -120)],&
& & & & & & & & & & & [NSValue
valueWithCGPoint:CGPointMake(512, 274)],&
& & & & & & & & & & & [NSValue
valueWithCGPoint:CGPointMake(512, 204)],&
& & & & & & & & & & & [NSValue
valueWithCGPoint:CGPointMake(512, 274)],&
& & & & & & & & & & & [NSValue
valueWithCGPoint:CGPointMake(512, 244)],&
& & & & & & & & & & & [NSValue
valueWithCGPoint:CGPointMake(512, 274)],
& & [animationKey
setValues:array];
& & [array
& & NSArray *times = [[NSArray
alloc] initWithObjects:
& & & & & & & & & & & [NSNumber
numberWithFloat:0.1f],&
& & & & & & & & & & & [NSNumber
numberWithFloat:0.25f],&
& & & & & & & & & & & [NSNumber
numberWithFloat:0.4f],&
& & & & & & & & & & & [NSNumber
numberWithFloat:0.6f],&
& & & & & & & & & & & [NSNumber
numberWithFloat:0.8f],&
& & & & & & & & & & & [NSNumber
numberWithFloat:1.0f],
& & [animationKey
setKeyTimes:times];
& & [times
& & [landingView.layer
addAnimation:animationKey
forKey:@&showLandView&];
/*&*&pointToAngle&按角度旋转&
*&@angel&CGFloat&角度&*&@duration&CGFloat&动画执行时间&
*/&&-&(void)&pointToAngle:(CGFloat)&angle&Duration:(CGFloat)&duration&&
{&&&&&&CAKeyframeAnimation&*anim=[CAKeyframeAnimation&animationWithKeyPath:@&transform&];&&&
&&&&NSMutableArray&*values=[NSMutableArray&array];&&&&&&&anim.duration&=&&&
&&&&anim.autoreverses&=&NO;&&&&&&anim.fillMode&=&kCAFillModeF&&
&&&&anim.remo

我要回帖

更多关于 如何添加打印机 的文章

 

随机推荐