1、app名称的修改
在info.plist中添加一个key(Bundle display name),Value就是你需要的新名字,Run后退回主页面,可以看到你的新App名字在这页面上了。
2、获取某个View所在的控制器
- (UIViewController *)viewController{
UIViewController *viewController = nil;
UIResponder *next = self.nextResponder;
while(next){
if([next isKindOfClass:[UIViewController class]]){
viewController = (UIViewController *)next;
break;
}
next = next.nextResponder;
}
return viewController;
}
3、两种方法删除NSUserDefaults所有记录
//方法一:
NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];
//方法二:
- (void)resetDefaults{
NSUserDefaults*defs = [NSUserDefaults standardUserDefaults];
NSDictionary* dic = [defs dictionaryRepresentation];
for(id key in dic) {
[defs removeObjectForKey:key];
}
[defssynchronize];
}
4、字符串反转
第一种:
- (NSString*)reverseWordsInString:(NSString*)str{
NSMutableString*newString = [[NSMutableString alloc]initWithCapacity:str.length];
for(NSInteger i = str.length-1; i >=0; i--) {
unicharch = [str characterAtIndex:i];
[newString appendFormat:@"%c", ch];
}
return newString;
}
第二种:
- (NSString*)reverseWordsInString:(NSString*)str{
NSMutableString *reverString = [NSMutableString stringWithCapacity:str.length];
[str enumerateSubstringsInRange:NSMakeRange(0, str.length)options:NSStringEnumerationReverse|NSStringEnumerationByComposedCharacterSequencesusingBlock:^(NSString*_Nullablesubstring,NSRangesubstringRange,NSRangeenclosingRange,BOOL*_Nonnullstop) {
[reverString appendString:substring];
}];
return reverString;
}
5、禁止锁屏
[UIApplication sharedApplication].idleTimerDisabled=YES;
或 [[UIApplication sharedApplication] setIdleTimerDisabled:YES];
6、iOS跳转到AppStore下载应用评分
[[UIApplication sharedApplication]openURL:[NSURLURLWithString:@"itms-apps://ituns.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=APPID"]];
7、中文转拼音
- (NSString*)transform:(NSString*)chinese{
//将NSString转换成NSMutableString
NSMutableString *pinyin = [chinese mutableCopy];
//将汉字转换为拼音(带音标)
CFStringTransform((__bridgeCFMutableStringRef)pinyin,NULL,kCFStringTransformToLatin,NO);
NSLog(@"pin yin%@",pinyin);
//去掉拼音的音标
CFStringTransform((__bridgeCFMutableStringRef)pinyin,NULL,kCFStringTransformStripCombiningMarks,NO);
NSLog(@"qu yin biao%@", pinyin);
//返回最近结果
return pinyin;
}
8、手动更改iOS状态栏的颜色
- (void)setStatusBarBackgroundColor:(UIColor*)color{
UIView*statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
if([statusBar respondsToSelector:@selector(setBackgroundColor:)]) {
statusBar.backgroundColor= color;
}
}
9、判断当前ViewController是push还是present的方式显示的
NSArray*viewControllers =self.navigationController.viewControllers;
if(viewControllers.count>1) {
if([viewControllrs objectAtIndex:viewControllers.count-1] ==self) {
//push方式
[self.navigationController popViewControllerAnimated:YES];
}
}
else{
//present方式
[self dismissViewControllerAnimated:YEScompletion:nil];
}
10、iOS在当前屏幕获取第一响应
UIWindow*keyWindow = [[UIApplication sharedApplication] keyWindow];
UIView*firstResponder = [keyWindow performSelector:@selector(firstResponder)];
11、判断对象是否遵循了某协议
if([self.selectedController conformsToProtocol:@protocol(RefreshProtocol)]) {
[self.selectedController performSelector:@selector(onTriggerRefresh)];
}
12、判断view是不是指定视图的子视图
BOOL isView = [textView isDescendantOfView:self.view];
13、NSArray 快速求总和, 最大值, 最小值, 平均值
NSArray*array = [NSArrayarrayWithObjects:@"2.0",@"2.3",@"3.0",@"4.0",@"10",nil];
CGFloatsum = [[arrayvalueForKeyPath:@"@sum.floatValue"]floatValue];
CGFloatavg = [[arrayvalueForKeyPath:@"@avg.floatValue"]floatValue];
CGFloatmax = [[arrayvalueForKeyPath:@"@max.floatValue"]floatValue];
CGFloatmin = [[arrayvalueForKeyPath:@"@min.floatValue"]floatValue];
14、获取一个类的所有子类(需要引入runtime.h)
+ (NSArray*)allSubclasses{
Class myClass = [selfclass];
NSMutableArray*mySubclasses = [NSMutableArrayarray];
unsigned int numOfClasses;
Class *classes =objc_copyClassList(&numOfClasses);
for(unsigned int ci =0; ci < numOfClasses; ci++) {
Class superClass = classes[ci];
do{
superClass =class_getSuperclass(superClass);
}while(superClass && superClass != myClass);
if(superClass) {
[mySubclassesaddObject:classes[ci]];
}
}
free(classes);
return mySubclasses;
}
15、取消UICollectionView的隐式动画
[UIViewperformWithoutAnimation:^{
[collectionView reloadItemsAtIndexPaths:@[indexpath indexpathForItem:index inSection:0]];
}];
16、UIImage占用内存大小
UIImage*image = [UIImageimageNamed:@"a"];
NSUIntegersize =CGImageGetHeight(image.CGImage) *CGBitmapContextGetBytesPerRow(image.CGImage);
17、GCD timer 定时器
dispatch_queue_tqueue =dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);
dispatch_source_ttimer =dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,0,0, queue);
dispatch_source_set_timer(timer,dispatch_walltime(NULL,0),1.0*NSEC_PER_SEC,0);//每秒执行
dispatch_source_set_event_handler(timer, ^{
//@"倒计时结束,关闭"
dispatch_source_cancel(timer);
dispatch_async(dispatch_get_main_queue(), ^{
//回主线程
});
});
18、图片上绘制文字 属于UIImage的Category
- (UIImage*)imageWithTitle:(NSString*)title fontSize:(CGFloat)fontSize{
//画布大小
CGSizesize =CGSizeMake(self.size.width,self.size.height);
//创建一个基于位图的上下文
UIGraphicsBeginImageContextWithOptions(size,NO,0.0);//opaque:NO scale:0.0
[selfdrawAtPoint:CGPointMake(0,0)];
//文字居中显示在画布上
NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle]mutableCopy];
paragraphStyle.lineBreakMode=NSLineBreakByCharWrapping;
paragraphStyle.alignment=NSTextAlignmentCenter;//文字居中
//计算文字所占的size,文字居中显示在画布上
CGSizesizeText = [title boundingRectWithSize:self.sizeoptions:NSStringDrawingUsesLineFragmentOriginattributes:@{NSFontAttributeName:[UIFont systemFontOfSize:fontSize]}context:nil].size;
CGFloatwidth =self.size.width;
CGFloatheight =self.size.height;
CGRectrect =CGRectMake((width - sizeText.width)/2, (height -sizeText.height)/2, sizeText.width, sizeText.height);
//绘制文字
[title drawInRect:rectwithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:fontSize],NSForegroundColorAttributeName:[UIColor whiteColor],NSParagraphStyleAttributeName:paragraphStyle}];
//返回绘制的新图形
UIImage*newImage =UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
returnnewImage;
}
19、查找一个视图的所有子视图
- (NSMutableArray*)allSubViewsForView:(UIView*)view{
NSMutableArray *array = [NSMutableArray arrayWithCapacity:0];
for(UIView *subView in view.subviews) {
[array addObject:subView];
subviews.count>0) {
[array addObjectsFromArray:[self allSubViewsForView:subView]];
}
}
return array;
}
20、按比例缩放,size 是你要把图显示到 多大区域CGSizeMake(300, 140)
- (UIImage *) imageCompressForSize:(UIImage *)sourceImage targetSize:(CGSize)size{
UIImage *newImage = nil;
CGSize imageSize = sourceImage.size;
CGFloat width = imageSize.width;
CGFloat height = imageSize.height;
CGFloat targetWidth = size.width;
CGFloat targetHeight = size.height;
CGFloat scaleFactor = 0.0;
CGFloat scaledWidth = targetWidth;
CGFloat scaledHeight = targetHeight;
CGPoint thumbnailPoint = CGPointMake(0.0, 0.0);
if(CGSizeEqualToSize(imageSize, size) == NO){
CGFloat widthFactor = targetWidth / width;
CGFloat heightFactor = targetHeight / height;
if(widthFactor > heightFactor){
scaleFactor = widthFactor;
}
else{
scaleFactor = heightFactor;
}
scaledWidth = width * scaleFactor;
scaledHeight = height * scaleFactor;
if(widthFactor > heightFactor){
thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
}else if(widthFactor < heightFactor){
thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
}
}
UIGraphicsBeginImageContext(size);
CGRect thumbnailRect = CGRectZero;
thumbnailRect.origin = thumbnailPoint;
thumbnailRect.size.width = scaledWidth;
thumbnailRect.size.height = scaledHeight;
[sourceImage drawInRect:thumbnailRect];
newImage = UIGraphicsGetImageFromCurrentImageContext();
if(newImage == nil){
NSLog(@"scale image fail");
}
UIGraphicsEndImageContext();
return newImage;
}
21、指定宽度按比例缩放
- (UIImage*) imageCompressForWidth:(UIImage*)sourceImage targetWidth:(CGFloat)defineWidth{
UIImage*newImage =nil;
CGSizeimageSize = sourceImage.size;
CGFloatwidth = imageSize.width;
CGFloatheight = imageSize.height;
CGFloattargetWidth = defineWidth;
CGFloattargetHeight = height / (width / targetWidth);
CGSizesize =CGSizeMake(targetWidth, targetHeight);
CGFloatscaleFactor =0.0;
CGFloatscaledWidth = targetWidth;
CGFloatscaledHeight = targetHeight;
CGPointthumbnailPoint =CGPointMake(0.0,0.0);
if(CGSizeEqualToSize(imageSize, size) ==NO){
CGFloatwidthFactor = targetWidth / width;
CGFloatheightFactor = targetHeight / height;
if(widthFactor > heightFactor){
scaleFactor = widthFactor;
}
else{
scaleFactor = heightFactor;
}
scaledWidth = width * scaleFactor;
scaledHeight = height * scaleFactor;
if(widthFactor > heightFactor){
thumbnailPoint.y= (targetHeight - scaledHeight) *0.5;
}elseif(widthFactor < heightFactor){
thumbnailPoint.x= (targetWidth - scaledWidth) *0.5;
}
}
UIGraphicsBeginImageContext(size);
CGRectthumbnailRect =CGRectZero;
thumbnailRect.origin= thumbnailPoint;
thumbnailRect.size.width= scaledWidth;
thumbnailRect.size.height= scaledHeight;
[sourceImagedrawInRect:thumbnailRect];
newImage =UIGraphicsGetImageFromCurrentImageContext();
if(newImage ==nil){
NSLog(@"scale image fail");
}
UIGraphicsEndImageContext();
return newImage;
}
22、textfield只能输入数字和小数点
- (BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString*)string{
////控制长度
//if(range.location>=25)
//return NO;
constchar* ch = [stringcStringUsingEncoding:NSUTF8StringEncoding];
if(*ch == 0)
return YES;
//字符0-9和.
if( *ch !=46&& ( *ch <48|| *ch >57) ){
return NO;
}//有了小数点
if([textField.textrangeOfString:@"."].length==1)
{
NSUInteger length=[textField.textrangeOfString:@"."].location;
//小数点后面两位小数且不能再是小数点
if([[textField.textsubstringFromIndex:length] length]>3|| *ch ==46){//3表示后面小数位的个数。。
return NO;
}
}
return YES;
}
23、
24、假设 i = 1 ,如果想用 i 除以100得到0.01的值:
i / 100.0 才会得到0.01。 整型除以浮点型,自动变浮点型。
25、把segment放在导航栏的中间
[self.navigationItem setTitleView:_segmentView];
26'//去掉UItableview headerview黏性(sticky)
- (void)scrollViewDidScroll:(UIScrollView*)scrollView {
if(scrollView ==self.mainTableView)
{
CGFloatsectionHeaderHeight =60;//sectionHeaderHeight
if(scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
scrollView.contentInset=UIEdgeInsetsMake(-scrollView.contentOffset.y,0,0,0);
}elseif(scrollView.contentOffset.y>=sectionHeaderHeight) {
scrollView.contentInset=UIEdgeInsetsMake(-sectionHeaderHeight,0,0,0);
}
}
}