在这里总结一些iOS开发中的小技巧,能大大方便我们的开发,持续更新。

UITableView的Group样式下顶部空白处理

//分组列表头部空白处理
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0.1)];
self.tableView.tableHeaderView = view;

UITableView的plain样式下,取消区头停滞效果

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat sectionHeaderHeight = sectionHead.height;
    if (scrollView.contentOffset.y=0)
    {
        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
    }
    else if(scrollView.contentOffset.y>=sectionHeaderHeight)
    {
        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
    }
}

那个,其实,还是用Group样式吧哈哈。

获取某个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;
}

两种方法删除NSUserDefaults所有记录

//方法一
NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];

//方法二
- (void)resetDefaults
{
    NSUserDefaults * defs = [NSUserDefaults standardUserDefaults];
    NSDictionary * dict = [defs dictionaryRepresentation];
    for (id key in dict)
    {
        [defs removeObjectForKey:key];
    }
    [defs synchronize];
}

打印系统所有已注册的字体名称

#pragma mark - 打印系统所有已注册的字体名称
void enumerateFonts()
{
    for(NSString *familyName in [UIFont familyNames])
   {
        NSLog(@"%@",familyName);
        NSArray *fontNames = [UIFont fontNamesForFamilyName:familyName];
        for(NSString *fontName in fontNames)
       {
            NSLog(@"\t|- %@",fontName);
       }
   }
}

获取图片某一点的颜色

- (UIColor*) getPixelColorAtLocation:(CGPoint)point inImage:(UIImage *)image
{

    UIColor* color = nil;
    CGImageRef inImage = image.CGImage;
    CGContextRef cgctx = [self createARGBBitmapContextFromImage:inImage];

    if (cgctx == NULL) {
        return nil; /* error */
    }
    size_t w = CGImageGetWidth(inImage);
    size_t h = CGImageGetHeight(inImage);
    CGRect rect = {{0,0},{w,h}};

    CGContextDrawImage(cgctx, rect, inImage);
    unsigned char* data = CGBitmapContextGetData (cgctx);
    if (data != NULL) {
        int offset = 4*((w*round(point.y))+round(point.x));
        int alpha =  data[offset];
        int red = data[offset+1];
        int green = data[offset+2];
        int blue = data[offset+3];
        color = [UIColor colorWithRed:(red/255.0f) green:(green/255.0f) blue:
                 (blue/255.0f) alpha:(alpha/255.0f)];
    }
    CGContextRelease(cgctx);
    if (data) {
        free(data);
    }
    return color;
}

字符串反转

第一种:
- (NSString *)reverseWordsInString:(NSString *)str
{
    NSMutableString *newString = [[NSMutableString alloc] initWithCapacity:str.length];
    for (NSInteger i = str.length - 1; i >= 0 ; i --)
    {
        unichar ch = [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 |NSStringEnumerationByComposedCharacterSequences  usingBlock:^(NSString *substring, NSRange substringRange,NSRange enclosingRange, BOOL *stop) {
          [reverString appendString:substring];
      }];
     return reverString;
}

禁止锁屏,

默认情况下,当设备一段时间没有触控动作时,iOS会锁住屏幕。但有一些应用是不需要锁屏的,比如视频播放器。

[UIApplication sharedApplication].idleTimerDisabled = YES;
或
[[UIApplication sharedApplication] setIdleTimerDisabled:YES];

模态推出透明界面

UIViewController *vc = [[UIViewController alloc] init];
UINavigationController *na = [[UINavigationController alloc] initWithRootViewController:vc];

if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
{
     na.modalPresentationStyle = UIModalPresentationOverCurrentContext;
}
else
{
     self.modalPresentationStyle=UIModalPresentationCurrentContext;
}

[self presentViewController:na animated:YES completion:nil];

Xcode调试不显示内存占用

editSCheme  里面有个选项叫叫做enable zoombie Objects  取消选中

显示隐藏文件

//显示
defaults write com.apple.finder AppleShowAllFiles -bool true
killall Finder

//隐藏
defaults write com.apple.finder AppleShowAllFiles -bool false
killall Finder

字符串按多个符号分割

iOS跳转到App Store下载应用评分

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=APPID"]];

iOS 获取汉字的拼音

+ (NSString *)transform:(NSString *)chinese
{
    //将NSString装换成NSMutableString
    NSMutableString *pinyin = [chinese mutableCopy];
    //将汉字转换为拼音(带音标)
    CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformMandarinLatin, NO);
    NSLog(@"%@", pinyin);
    //去掉拼音的音标
    CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformStripCombiningMarks, NO);
    NSLog(@"%@", pinyin);
    //返回最近结果
    return pinyin;
}

手动更改iOS状态栏的颜色

- (void)setStatusBarBackgroundColor:(UIColor *)color
{
    UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];

    if ([statusBar respondsToSelector:@selector(setBackgroundColor:)])
    {
        statusBar.backgroundColor = color;
    }
}

判断当前ViewController是push还是present的方式显示的

NSArray *viewcontrollers=self.navigationController.viewControllers;

if (viewcontrollers.count > 1)
{
    if ([viewcontrollers objectAtIndex:viewcontrollers.count - 1] == self)
    {
        //push方式
       [self.navigationController popViewControllerAnimated:YES];
    }
}
else
{
    //present方式
    [self dismissViewControllerAnimated:YES completion:nil];
}

获取实际使用的LaunchImage图片

- (NSString *)getLaunchImageName
{
    CGSize viewSize = self.window.bounds.size;
    // 竖屏
    NSString *viewOrientation = @"Portrait";
    NSString *launchImageName = nil;
    NSArray* imagesDict = [[[NSBundle mainBundle] infoDictionary] valueForKey:@"UILaunchImages"];
    for (NSDictionary* dict in imagesDict)
    {
        CGSize imageSize = CGSizeFromString(dict[@"UILaunchImageSize"]);
        if (CGSizeEqualToSize(imageSize, viewSize) && [viewOrientationisEqualToString:dict[@"UILaunchImageOrientation"]])
        {
            launchImageName = dict[@"UILaunchImageName"];
        }
    }
    return launchImageName;
}

iOS在当前屏幕获取第一响应

UIWindow * keyWindow = [[UIApplication sharedApplication] keyWindow];
UIView * firstResponder = [keyWindow performSelector:@selector(firstResponder)];

判断对象是否遵循了某协议

if ([self.selectedController conformsToProtocol:@protocol(RefreshPtotocol)])
{
     [self.selectedController performSelector:@selector(onTriggerRefresh)];
}

判断view是不是指定视图的子视图

BOOL isView = [textView isDescendantOfView:self.view];

NSArray 快速求总和 最大值 最小值 和 平均值

NSArray *array = [NSArray arrayWithObjects:@"2.0", @"2.3", @"3.0", @"4.0", @"10", nil];
CGFloat sum = [[array valueForKeyPath:@"@sum.floatValue"] floatValue];
CGFloat avg = [[array valueForKeyPath:@"@avg.floatValue"] floatValue];
CGFloat max =[[array valueForKeyPath:@"@max.floatValue"] floatValue];
CGFloat min =[[array valueForKeyPath:@"@min.floatValue"] floatValue];
NSLog(@"%f\n%f\n%f\n%f",sum,avg,max,min);

修改UITextField中Placeholder的文字颜色

[textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];

关于NSDateFormatter的格式

G: 公元时代,例如AD公元
yy: 年的后2位
yyyy: 完整年
MM: 月,显示为1-12
MMM: 月,显示为英文月份简写,如 Jan
MMMM: 月,显示为英文月份全称,如 Janualy
dd: 日,2位数表示,如02
d: 日,1-2位显示,如 2
EEE: 简写星期几,如Sun
EEEE: 全写星期几,如Sunday
aa: 上下午,AM/PM
H: 时,24小时制,0-23
K:时,12小时制,0-11
m: 分,1-2位
mm: 分,2位
s: 秒,1-2位
ss: 秒,2位
S: 毫秒

获取一个类的所有子类

+ (NSArray *) allSubclasses
{
    Class myClass = [self class];
    NSMutableArray *mySubclasses = [NSMutableArray array];
    unsigned int numOfClasses;
    Class *classes = objc_copyClassList(&numOfClasses;);
    for (unsigned int ci = 0; ci

监测IOS设备是否设置了代理,需要CFNetwork.framework

NSDictionary *proxySettings = (__bridge NSDictionary *)(CFNetworkCopySystemProxySettings());
NSArray *proxies = (__bridge NSArray *)(CFNetworkCopyProxiesForURL((__bridge CFURLRef _Nonnull)([NSURLURLWithString:@"http://www.baidu.com"]), (__bridge CFDictionaryRef _Nonnull)(proxySettings)));
NSLog(@"\n%@",proxies);

NSDictionary *settings = proxies[0];
NSLog(@"%@",[settings objectForKey:(NSString *)kCFProxyHostNameKey]);
NSLog(@"%@",[settings objectForKey:(NSString *)kCFProxyPortNumberKey]);
NSLog(@"%@",[settings objectForKey:(NSString *)kCFProxyTypeKey]);

if ([[settings objectForKey:(NSString *)kCFProxyTypeKey] isEqualToString:@"kCFProxyTypeNone"])
{
     NSLog(@"没代理");
}
else
{
     NSLog(@"设置了代理");
}

阿拉伯数字转中文格式

+(NSString *)translation:(NSString *)arebic
{
    NSString *str = arebic;
    NSArray *arabic_numerals = @[@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"0"];
    NSArray *chinese_numerals = @[@"一",@"二",@"三",@"四",@"五",@"六",@"七",@"八",@"九",@"零"];
    NSArray *digits = @[@"个",@"十",@"百",@"千",@"万",@"十",@"百",@"千",@"亿",@"十",@"百",@"千",@"兆"];
    NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:chinese_numerals forKeys:arabic_numerals];

    NSMutableArray *sums = [NSMutableArray array];
    for (int i = 0; i

Base64编码与NSString对象或NSData对象的转换

// Create NSData object
NSData *nsdata = [@"iOS Developer Tips encoded in Base64"
  dataUsingEncoding:NSUTF8StringEncoding];

// Get NSString from NSData object in Base64
NSString *base64Encoded = [nsdata base64EncodedStringWithOptions:0];

// Print the Base64 encoded string
NSLog(@"Encoded: %@", base64Encoded);

// Let‘s go the other way...

// NSData from the Base64 encoded str
NSData *nsdataFromBase64String = [[NSData alloc]
  initWithBase64EncodedString:base64Encoded options:0];

// Decoded NSString from the NSData
NSString *base64Decoded = [[NSString alloc]
  initWithData:nsdataFromBase64String encoding:NSUTF8StringEncoding];
NSLog(@"Decoded: %@", base64Decoded);

取消UICollectionView的隐式动画

UICollectionView在reloadItems的时候,默认会附加一个隐式的fade动画,有时候很讨厌,尤其是当你的cell是复合cell的情况下(比如cell使用到了UIStackView)。

下面几种方法都可以帮你去除这些动画

//方法一
[UIView performWithoutAnimation:^{
    [collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:index inSection:0]]];
}];

//方法二
[UIView animateWithDuration:0 animations:^{
    [collectionView performBatchUpdates:^{
        [collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:index inSection:0]]];
    } completion:nil];
}];

//方法三
[UIView setAnimationsEnabled:NO];
[self.trackPanel performBatchUpdates:^{
    [collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:index inSection:0]]];
} completion:^(BOOL finished) {
    [UIView setAnimationsEnabled:YES];
}];

让Xcode的控制台支持LLDB类型的打印

打开终端输入三条命令:
touch ~/.lldbinit
echo display @import UIKit >> ~/.lldbinit
echo target stop-hook add -o \"target stop-hook disable\" >> ~/.lldbinit

CocoaPods pod install/pod update更新慢的问题

pod install --verbose --no-repo-update
pod update --verbose --no-repo-update
如果不加后面的参数,默认会升级CocoaPods的spec仓库,加一个参数可以省略这一步,然后速度就会提升不少

UIImage 占用内存大小

UIImage *image = [UIImage imageNamed:@"aa"];
NSUInteger size  = CGImageGetHeight(image.CGImage) * CGImageGetBytesPerRow(image.CGImage);

GCD timer定时器

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_source_t timer = 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(), ^{

    });
});
dispatch_resume(timer);

  

时间: 2024-09-28 04:02:50

在这里总结一些iOS开发中的小技巧,能大大方便我们的开发,持续更新。的相关文章

知识点回顾-27个iOS开发中的小技巧

★27个iOS开发中的小技巧 1.不想让TableView显示无用的Cell分割线怎么办? self.tableView.tableFooterView = [[UIView alloc] init]; 2.自定义了leftBarbuttonItem左滑返回手势失效了怎么办? self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:img style:UIBarButtonItemStylePl

Linux以及Android开发中的小技巧和长繁命令记录收集

不断更新收集中.... 2014071743 ssh以nx_guest的身份登录到172.24.221.137,然后在172.24.221.137与172.24.61.252的8080端口建立网络连接,同时创建端口为5678的本地代理服务 ssh -C -f -N -o 'TCPKeepAlive=yes' -L 5678:172.24.61.252:8080 [email protected] 反编译android下的二进制程序 ./prebuilts/gcc/linux-x86/arm/ar

iOS开发过程中的小技巧

转载自:http://blog.csdn.net/a451493485/article/details/8598839 iphone程序中实现截屏的一种方法在iphone程序中实现截屏的一种方法: //导入头文件#import QuartzCore/QuartzCore.h//将整个self.view大小的图层形式创建一张图片image UIGraphicsBeginImageContext(self.view.bounds.size):[self.view.layer renderInCont

Android开发中的小技巧

转自:http://blog.csdn.net/guxiao1201/article/details/40655661 简介: startActivities (Intent[] intents) setError (CharSequence error) 动画reverse () addLinks (TextView text, int mask) SystemClock public static void sleep (long ms) registerActivityLifecycleC

一些IOS开发中的小技巧

1.打包后提交爆错误 错误信息:ERROR ITMS-90035: "Invalid Signature. Code object is not signed at all. The binary at path [******.app/build-libidn.sh] 解决方案:在Archive 界面上 选择刚生成的那个app 右键 Show in Finder  显示包含内容->Products->Application->应用 右键显示包含内容,找到文件 build-li

Android 开发中常用小技巧

TextView中的getTextSize返回值是以像素(px)为单位的, 而setTextSize()是以sp为单位的. 所以如果直接用返回的值来设置会出错,解决办法是 用setTextSize()的另外一种形式,可以指定单位: 在继承自View时,绘制bitmap时,需要将图片放到新建的drawable-xdpi 中,否则容易出现绘制大小发生改变 在文字中加下划线: textView.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG); scro

asp.net开发中遇到的奇葩bug及解决办法(会持续更新。。。)

1,不知道你们遇没遇到过,在vs2010或更高版本上运行程序的时候,完全没问题,放在IIS中出现了问题,就比如左侧是菜单项,点击菜单右边显示,如果菜单链接是这样:content.aspx,而另一个链接是这样:manager/manager_list.aspx,在IIS中就会出现Session过期的问题,content.aspx页面根本无法接收到传过来的session值,因此会报session相关的错. 解决办法:把链接路径改成一致就能解决,改成这样:manager/content.aspx.暂时

开发中一些小技巧 - 递归打印子视图

1 // 递归获取子视图 2 - (void)getSub:(UIView *)view andLevel:(int)level { 3 NSArray *subviews = [view subviews]; 4 5 // 如果没有子视图就直接返回 6 if ([subviews count] == 0) return; 7 8 for (UIView *subview in subviews) { 9 10 // 根据层级决定前面空格个数,来缩进显示 11 NSString *blank =

Android开发中这些小技巧

http://blog.csdn.net/guxiao1201/article/details/40655661 http://blog.csdn.net/guxiao1201/article/details/40659561 http://blog.csdn.net/guxiao1201/article/details/40707815 http://blog.csdn.net/guxiao1201/article/details/40708775 http://blog.csdn.net/g