iOS中你可能你不知道的事歌词含义含义的几点设置

iOS中你可能不知道含义的几点设置iOS中你可能不知道含义的几点设置果粉指南百家号iOS中的一些大功能如Animoji、Apple Pay等,很多人都知道并且了解。但iOS设置中有一些藏得很深的小功能也很有意思,简单的来看一看吧。“启用WAPI”「设置-WiFi-启用WAPI」WAPI是中国无线局域网强制性标准中的安全机制,主要的作用是提升无线局域网的安全性,对普通的用户作用不大,但如果设备在局域网中,还是建议开启。启用WAPI以后,主要是增强WiFi的安全性,并不影响上网,所以不管开启还是关闭WAPI,对个人来说,都没有明显的变化。但对于大型终端而言,还是非常有用的。“WiFi助理”「设置-蜂窝数据-WiFi助理」WiFi助理可以在无线信号较弱的情况下自动切换为蜂窝移动数据,从而让用户更流畅的上网。简而言之就是当你的WiFi信号较弱时,系统会直接走流量上网,虽然现在都是无限流量卡了,流量少的同学还是关了吧。“引导式访问”「设置-通用-辅助功能-引导式访问」官方介绍的是:引导式访问可以让iPhone或iPad停留在单个应用程序中,并允许您控制其中可用的功能。简而言之,你可以控制iPhone只停留在一个应用中,并且可以控制停用应用内的功能。举个例子:你要把手机借给他人使用某个App,你可以只让手机停在这个App内,还可以禁用Home键、禁用屏幕的某些区域、禁止关机、禁止切换应用等等。这个功能在学校里老师使用iPad教学的时候很好用,或者父母把手机给小孩子玩的时候能避免小孩子乱按等等。“拨号助理”「设置-电话-拨号助理」这个功能对经常出国旅行的用户来说很棒。拨号助理会在你打电话时自动加上国家代码或本地区号。旅行途中,打电话时加上正确的前缀代码是非常重要的。举个例子:关闭该功能,就会直接呼出输入的号码(137***);开启该功能,会自动补足前面的代码前缀(+86137***)。“Handoff”「设置-通用-Handoff」Handoff保证了苹果生态系统上的任务能更加无缝的执行,这个功能需要多台登陆为同一iCloud账户并处于同一局域网内的苹果设备。开启该功能后,你在一个设备上使用某个App(如“邮件”“短信”),在某次中断后,你可以通过其他设备在你停止的位置上继续使用。举个例子:你在Mac上写邮件,这时你会在iPhone的锁定界面左下角看到邮件图标(邮箱账户相同时)。点击它,你就可以在手机上继续编写你的邮件。反之也是一样,中断手机上的操作也能在Mac或iPad上继续,前提是设备处于同一iCloud账户并在同一局域网下。本文由百家号作者上传并发布,百家号仅提供信息发布平台。文章仅代表作者个人观点,不代表百度立场。未经作者许可,不得转载。果粉指南百家号最近更新:简介:分享苹果周边,聚焦科技热点。作者最新文章相关文章在 SegmentFault,学习技能、解决问题
每个月,我们帮助 1000 万的开发者解决各种各样的技术问题。并助力他们在技术能力、职业生涯、影响力上获得提升。
问题对人有帮助,内容完整,我也想知道答案
问题没有实际价值,缺少关键内容,没有改进余地
iOS9中不设置info.plist,能使用HTTP请求吗?
答案对人有帮助,有参考价值
答案没帮助,是错误的答案,答非所问
可以的,App Transport Security,只是苹果对NSURL这一层做的处理,所以我们使用CFNetwork做网络处理的话,苹果就干涉不到了。目前解决在iOS9中使用HTTP请求有下面两种方法:1、在Info.plist中添加NSAppTransportSecurity类型Dictionary,在NSAppTransportSecurity下添加NSAllowsArbitraryLoads,Boolean为YES。2、直接使用CFNetwork做网络请求,ASIHTTPRequest就是基于CFNetwotk做的封装,如果有需求的同学可以看看ASI里面的源码,如果某个时间段你又想要使用HTTPS的话,ASI对SSL/TSL的证书验证有点问题,证书验证还得自己封装一下才行。刚才我说道,ATS是苹果针对与NSURL这一层做的封装,所以我们使用CFNetwork或者更底层做网络请求的话是不受ATS限制的。
答案对人有帮助,有参考价值
答案没帮助,是错误的答案,答非所问
Socket什么的应该都可以吧
分享到微博?
关闭理由:
删除理由:
忽略理由:
推广(招聘、广告、SEO 等)方面的内容
与已有问题重复(请编辑该提问指向已有相同问题)
答非所问,不符合答题要求
宜作评论而非答案
带有人身攻击、辱骂、仇恨等违反条款的内容
无法获得确切结果的问题
非开发直接相关的问题
非技术提问的讨论型问题
其他原因(请补充说明)
我要该,理由是:
在 SegmentFault,学习技能、解决问题
每个月,我们帮助 1000 万的开发者解决各种各样的技术问题。并助力他们在技术能力、职业生涯、影响力上获得提升。iOS小技巧总结,有你不知道的么
iOS小技巧总结,有你不知道的么
在这里总结一些iOS开发中的小技巧,能大大方便我们的开发,持续更新。
UITableView的Group样式下顶部空白处理
//分组列表头部空白处理
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0.1)];
self.tableView.tableHeaderView =
在这里总结一些iOS开发中的小技巧,能大大方便我们的开发,持续更新。
UITableView的Group样式下顶部空白处理
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0.1)];
self.tableView.tableHeaderView =
UITableView的plain样式下,取消区头停滞效果
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
CGFloat sectionHeaderHeight = sectionHead.
if (scrollView.contentOffset.y&=sectionHeaderHeight&&scrollV.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.nextR
while (next)
if ([next isKindOfClass:[UIViewController class]])
viewController = (UIViewController *)next;
next = next.nextR
return viewC
两种方法删除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;
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);
字符串反转
- (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 newS
- (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 reverS
禁止锁屏,
默认情况下,当设备一段时间没有触控动作时,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;
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
NSMutableString *pinyin = [chinese mutableCopy];
CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformMandarinLatin, NO);
NSLog(@"%@", pinyin);
CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformStripCombiningMarks, NO);
NSLog(@"%@", pinyin);
手动更改iOS状态栏的颜色
- (void)setStatusBarBackgroundColor:(UIColor *)color
UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
if ([statusBar respondsToSelector:@selector(setBackgroundColor:)])
statusBar.backgroundColor =
判断当前ViewController是push还是present的方式显示的
NSArray *viewcontrollers=self.navigationController.viewControllers;
if (viewcontrollers.count & 1)
if ([viewcontrollers objectAtIndex:viewcontrollers.count - 1] == self)
[self.navigationController popViewControllerAnimated:YES];
[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) && [viewOrientation isEqualToString:dict[@"UILaunchImageOrientation"]])
launchImageName = dict[@"UILaunchImageName"];
return launchImageN
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位
获取一个类的所有子类
+ (NSArray *) allSubclasses
Class myClass = [self class];
NSMutableArray *mySubclasses = [NSMutableArray array];
unsigned int numOfC
Class *classes = objc_copyClassList(&numOfC);
for (unsigned int ci = 0; ci & numOfC ci++)
Class superClass = classes[ci];
superClass = class_getSuperclass(superClass);
} while (superClass && superClass != myClass);
if (superClass)
[mySubclasses addObject: classes[ci]];
free(classes);
return myS
监测IOS设备是否设置了代理,需要CFNetwork.framework
NSDictionary *proxySettings = (__bridge NSDictionary *)(CFNetworkCopySystemProxySettings());
NSArray *proxies = (__bridge NSArray *)(CFNetworkCopyProxiesForURL((__bridge CFURLRef _Nonnull)([NSURL URLWithString:@"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(@"没代理");
NSLog(@"设置了代理");
阿拉伯数字转中文格式
+(NSString *)translation:(NSString *)arebic
NSString *str =
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 & str.length; i ++) {
NSString *substr = [str substringWithRange:NSMakeRange(i, 1)];
NSString *a = [dictionary objectForKey:substr];
NSString *b = digits[str.length -i-1];
NSString *sum = [a stringByAppendingString:b];
if ([a isEqualToString:chinese_numerals[9]])
if([b isEqualToString:digits[4]] || [b isEqualToString:digits[8]])
if ([[sums lastObject] isEqualToString:chinese_numerals[9]])
[sums removeLastObject];
sum = chinese_numerals[9];
if ([[sums lastObject] isEqualToString:sum])
[sums addObject:sum];
NSString *sumStr = [sums componentsJoinedByString:@""];
NSString *chinese = [sumStr substringToIndex:sumStr.length-1];
NSLog(@"%@",str);
NSLog(@"%@",chinese);
Base64编码与NSString对象或NSData对象的转换
NSData *nsdata = [@"iOS Developer Tips encoded in Base64"
dataUsingEncoding:NSUTF8StringEncoding];
NSString *base64Encoded = [nsdata base64EncodedStringWithOptions:0];
NSLog(@"Encoded: %@", base64Encoded);
NSData *nsdataFromBase64String = [[NSData alloc]
initWithBase64EncodedString:base64Encoded options:0];
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
pod 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);
图片上绘制文字 写一个UIImage的category
- (UIImage *)imageWithTitle:(NSString *)title fontSize:(CGFloat)fontSize
CGSize size=CGSizeMake(self.size.width,self.size.height);
UIGraphicsBeginImageContextWithOptions(size,NO,0.0);
[self drawAtPoint:CGPointMake(0.0,0.0)];
NSMutableParagraphStyle* paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;
paragraphStyle.alignment=NSTextAlignmentCenter;
CGSize sizeText=[title boundingRectWithSize:self.size options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:fontSize]}context:nil].size;
CGFloat width = self.size.width;
CGFloat height = self.size.height;
CGRect rect = CGRectMake((width-sizeText.width)/2, (height-sizeText.height)/2, sizeText.width, sizeText.height);
[title drawInRect:rect withAttributes:@{ NSFontAttributeName:[UIFont systemFontOfSize:fontSize],NSForegroundColorAttributeName:[ UIColor whiteColor],NSParagraphStyleAttributeName:paragraphStyle}];
UIImage *newImage= UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newI
查找一个视图的所有子视图
- (NSMutableArray *)allSubViewsForView:(UIView *)view
NSMutableArray *array = [NSMutableArray arrayWithCapacity:0];
for (UIView *subView in view.subviews)
[array addObject:subView];
if (subView.subviews.count & 0)
[array addObjectsFromArray:[self allSubViewsForView:subView]];
计算文件大小
- (long long)fileSizeAtPath:(NSString *)path
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:path])
long long size = [fileManager attributesOfItemAtPath:path error:nil].fileSize;
- (long long)folderSizeAtPath:(NSString *)path
NSFileManager *fileManager = [NSFileManager defaultManager];
long long folderSize = 0;
if ([fileManager fileExistsAtPath:path])
NSArray *childerFiles = [fileManager subpathsAtPath:path];
for (NSString *fileName in childerFiles)
NSString *fileAbsolutePath = [path stringByAppendingPathComponent:fileName];
if ([fileManager fileExistsAtPath:fileAbsolutePath])
long long size = [fileManager attributesOfItemAtPath:fileAbsolutePath error:nil].fileSize;
folderSize +=
return folderS
UIView设置部分圆角
你是不是也遇到过这样的问题,一个button或者label,只要右边的两个角圆角,或者只要一个圆角。该怎么办呢。这就需要图层蒙版来帮助我们了
CGRect rect = view.bounds;
CGSize radio = CGSizeMake(30, 30);
UIRectCorner corner = UIRectCornerTopLeft|UIRectCornerTopRight;
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:rect byRoundingCorners:corner cornerRadii:radio];
CAShapeLayer *masklayer = [[CAShapeLayer alloc]init];
masklayer.frame = view.bounds;
masklayer.path = path.CGPath;
view.layer.mask =
取上整与取下整
floor(x),有时候也写做Floor(x),其功能是“下取整”,即取不大于x的最大整数 例如:
x=3.14,floor(x)=3
y=9.99999,floor(y)=9
与floor函数对应的是ceil函数,即上取整函数。
ceil函数的作用是求不小于给定实数的最小整数。
ceil(2)=ceil(1.2)=cei(1.5)=2.00
floor函数与ceil函数的返回值均为double型
计算字符串字符长度,一个汉字算两个字符
- (int)convertToInt:(NSString*)strtemp
int strlength = 0;
char* p = (char*)[strtemp cStringUsingEncoding:NSUnicodeStringEncoding];
for (int i=0 ; i&[strtemp lengthOfBytesUsingEncoding:NSUnicodeStringEncoding] ;i++)
strlength++;
-(NSUInteger) unicodeLengthOfString: (NSString *) text
NSUInteger asciiLength = 0;
for (NSUInteger i = 0; i & text.length; i++)
unichar uc = [text characterAtIndex: i];
asciiLength += isascii(uc) ? 1 : 2;
return asciiL
给UIView设置图片
UIImage *image = [UIImage imageNamed:@"image"];
self.MYView.layer.contents = (__bridge id _Nullable)(image.CGImage);
self.MYView.layer.contentsRect = CGRectMake(0, 0, 0.5, 0.5);
防止scrollView手势覆盖侧滑手势
[scrollView.panGestureRecognizerrequireGestureRecognizerToFail:self.navigationController.interactivePopGestureRecognizer];
去掉导航栏返回的back标题
[[UIBarButtonItemappearance]setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60)forBarMetrics:UIBarMetricsDefault];
字符串中是否含有中文
+ (BOOL)checkIsChinese:(NSString *)string
for (int i=0; i&string. i++)
unichar ch = [string characterAtIndex:i];
if (0x4E00 &= ch
&& ch &= 0x9FA5)
return YES;
return NO;
dispatch_group的使用
dispatch_group_t dispatchGroup = dispatch_group_create()
dispatch_group_enter(dispatchGroup)
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
NSLog(@"第一个请求完成");
dispatch_group_leave(dispatchGroup);
dispatch_group_enter(dispatchGroup);
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
NSLog(@"第二个请求完成")
dispatch_group_leave(dispatchGroup)
dispatch_group_notify(dispatchGroup, dispatch_get_main_queue(), ^(){
NSLog(@"请求完成")
UITextField每四位加一个空格,实现代理
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
if ([string isEqualToString:@""])
if ((textField.text.length - 2) % 5 == 0)
textField.text = [textField.text substringToIndex:textField.text.length - 1];
return YES;
if (textField.text.length % 5 == 0)
textField.text = [NSString stringWithFormat:@"%@ ", textField.text];
return YES;
获取私有属性和成员变量 #import &objc/runtime.h&
- (void)setTextColor
unsigned int count = 0;
objc_property_t *propertys = class_copyPropertyList([UIDatePicker class], &count);
for(int i = 0;i &i ++)
objc_property_t property = propertys[i];
NSString *propertyName = [NSString stringWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
NSLog(@"propertyname = %@",propertyName);
if ([propertyName isEqualToString:@"textColor"])
[datePicker setValue:[UIColor whiteColor] forKey:propertyName];
unsigned int count = 0;
Ivar *ivars = class_copyIvarList([UIAlertAction class], &count);
for(int i =0;i &i ++)
Ivar ivar = ivars[i];
NSString *ivarName = [NSString stringWithCString:ivar_getName(ivar) encoding:NSUTF8StringEncoding];
NSLog(@"uialertion.ivarName = %@",ivarName);
if ([ivarName isEqualToString:@"_titleTextColor"])
[alertOk setValue:[UIColor blueColor] forKey:@"titleTextColor"];
[alertCancel setValue:[UIColor purpleColor] forKey:@"titleTextColor"];
获取手机安装的应用
Class c =NSClassFromString(@"LSApplicationWorkspace");
id s = [(id)c performSelector:NSSelectorFromString(@"defaultWorkspace")];
NSArray *array = [s performSelector:NSSelectorFromString(@"allInstalledApplications")];
for (id item in array)
NSLog(@"%@",[item performSelector:NSSelectorFromString(@"applicationIdentifier")]);
NSLog(@"%@",[item performSelector:NSSelectorFromString(@"bundleVersion")]);
NSLog(@"%@",[item performSelector:NSSelectorFromString(@"shortVersionString")]);
判断两个日期是否在同一周 写在NSDate的category里面
- (BOOL)isSameDateWithDate:(NSDate *)date
if (fabs([self timeIntervalSinceDate:date]) &= 7 * 24 *3600)
return NO;
NSCalendar *calender = [NSCalendar currentCalendar];
calender.firstWeekday = 2;
NSUInteger countSelf = [calender ordinalityOfUnit:NSCalendarUnitWeekday inUnit:NSCalendarUnitYear forDate:self];
NSUInteger countDate = [calender ordinalityOfUnit:NSCalendarUnitWeekday inUnit:NSCalendarUnitYear forDate:date];
return countSelf == countD
应用内打开系统设置界面
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
//iOS8之前
//先添加一个url type如下图,在代码中调用如下代码,即可跳转到设置页面的对应项
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=WIFI"]];
可选值如下:
About — prefs:root=General&path=About
Accessibility — prefs:root=General&path=ACCESSIBILITY
Airplane Mode On — prefs:root=AIRPLANE_MODE
Auto-Lock — prefs:root=General&path=AUTOLOCK
Brightness — prefs:root=Brightness
Bluetooth — prefs:root=General&path=Bluetooth
Date & Time — prefs:root=General&path=DATE_AND_TIME
FaceTime — prefs:root=FACETIME
General — prefs:root=General
Keyboard — prefs:root=General&path=Keyboard
iCloud — prefs:root=CASTLE
iCloud Storage & Backup — prefs:root=CASTLE&path=STORAGE_AND_BACKUP
International — prefs:root=General&path=INTERNATIONAL
Location Services — prefs:root=LOCATION_SERVICES
Music — prefs:root=MUSIC
Music Equalizer — prefs:root=MUSIC&path=EQ
Music Volume Limit — prefs:root=MUSIC&path=VolumeLimit
Network — prefs:root=General&path=Network
Nike + iPod — prefs:root=NIKE_PLUS_IPOD
Notes — prefs:root=NOTES
Notification — prefs:root=NOTIFICATI*****_ID
Phone — prefs:root=Phone
Photos — prefs:root=Photos
Profile — prefs:root=General&path=ManagedConfigurationList
Reset — prefs:root=General&path=Reset
Safari — prefs:root=Safari
Siri — prefs:root=General&path=Assistant
Sounds — prefs:root=Sounds
Software Update — prefs:root=General&path=SOFTWARE_UPDATE_LINK
Store — prefs:root=STORE
Twitter — prefs:root=TWITTER
Usage — prefs:root=General&path=USAGE
VPN — prefs:root=General&path=Network/VPN
Wallpaper — prefs:root=Wallpaper
Wi-Fi — prefs:root=WIFI
动画暂停再开始
-(void)pauseLayer:(CALayer *)layer
CFTimeInterval pausedTime = [layer convertTime:CACurrentMediaTime() fromLayer:nil];
layer.speed = 0.0;
layer.timeOffset = pausedT
-(void)resumeLayer:(CALayer *)layer
CFTimeInterval pausedTime = [layer timeOffset];
layer.speed = 1.0;
layer.timeOffset = 0.0;
layer.beginTime = 0.0;
CFTimeInterval timeSincePause = [layer convertTime:CACurrentMediaTime() fromLayer:nil] - pausedT
layer.beginTime = timeSinceP
fillRule原理
iOS中数字的格式化
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterDecimalS
NSString *string = [formatter stringFromNumber:[NSNumber numberWithInt:]];
NSLog(@"Formatted number string:%@",string);
typedef NS_ENUM(NSUInteger, NSNumberFormatterStyle) {
NSNumberFormatterNoStyle = kCFNumberFormatterNoStyle,
NSNumberFormatterDecimalStyle = kCFNumberFormatterDecimalStyle,
NSNumberFormatterCurrencyStyle = kCFNumberFormatterCurrencyStyle,
NSNumberFormatterPercentStyle = kCFNumberFormatterPercentStyle,
NSNumberFormatterScientificStyle = kCFNumberFormatterScientificStyle,
NSNumberFormatterSpellOutStyle = kCFNumberFormatterSpellOutStyle
[1243:403] Formatted number string:
[1243:403] Formatted number string:123,456,789
[1243:403] Formatted number string:¥123,456,789.00
[1243:403] Formatted number string:-539,222,988%
[1243:403] Formatted number string:1.
[1243:403] Formatted number string:一亿二千三百四十五万六千七百八十九
如何获取WebView所有的图片地址,
在网页加载完成时,通过js获取图片和添加点击的识别方式
- (void)webViewDidFinishLoad:(UIWebView *)webView
NSString * const jsGetImages =
@"function getImages(){\
var objs = document.getElementsByTagName(\"img\");\
var imgScr = '';\
for(var i=0;i&objs.i++){\
imgScr = imgScr + objs[i].src + '+';\
return imgS\
[webView stringByEvaluatingJavaScriptFromString:jsGetImages];
NSString *urlResult = [webView stringByEvaluatingJavaScriptFromString:@"getImages()"];
NSArray *urlArray = [NSMutableArray arrayWithArray:[urlResult componentsSeparatedByString:@"+"]];
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation
NSString * const jsGetImages =
@"function getImages(){\
var objs = document.getElementsByTagName(\"img\");\
var imgScr = '';\
for(var i=0;i&objs.i++){\
imgScr = imgScr + objs[i].src + '+';\
return imgS\
[webView evaluateJavaScript:jsGetImages completionHandler:nil];
[webView evaluateJavaScript:@"getImages()" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
NSLog(@"%@",result);
获取到webview的高度
CGFloat height = [[self.webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] floatValue];
navigationBar变为纯透明
[self.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
self.navigationBar.shadowImage = [UIImage new];
[[self.navigationBar subviews] objectAtIndex:0].alpha = 0;
tabBar同理
[self.tabBar setBackgroundImage:[UIImage new]];
self.tabBar.shadowImage = [UIImage new];
navigationBar根据滑动距离的渐变色实现
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
CGFloat offsetToShow = 200.0;
CGFloat alpha = 1 - (offsetToShow - scrollView.contentOffset.y) / offsetToS
[[self.navigationController.navigationBar subviews] objectAtIndex:0].alpha =
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
CGFloat offsetToShow = 200.0;
CGFloat alpha = 1 - (offsetToShow - scrollView.contentOffset.y) / offsetToS
[self.navigationController.navigationBar setShadowImage:[UIImage new]];
[self.navigationController.navigationBar setBackgroundImage:[self imageWithColor:[[UIColor orangeColor]colorWithAlphaComponent:alpha]] forBarMetrics:UIBarMetricsDefault];
- (UIImage *)imageWithColor:(UIColor *)color
CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect);
UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return theI
iOS 开发中一些相关的路径
模拟器的位置:
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs
文档安装位置:
/Applications/Xcode.app/Contents/Developer/Documentation/DocSets
插件保存路径:
~/Library/ApplicationSupport/Developer/Shared/Xcode/Plug-ins
自定义代码段的保存路径:
~/Library/Developer/Xcode/UserData/CodeSnippets/
如果找不到CodeSnippets文件夹,可以自己新建一个CodeSnippets文件夹。
描述文件路径
~/Library/MobileDevice/Provisioning Profiles
navigationItem的BarButtonItem如何紧靠屏幕右边界或者左边界?
一般情况下,右边的item会和屏幕右侧保持一段距离:
下面是通过添加一个负值宽度的固定间距的item来解决,也可以改变宽度实现不同的间隔:
UIImage *img = [[UIImage imageNamed:@"icon_cog"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
UIBarButtonItem *rightNegativeSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
[rightNegativeSpacer setWidth:-15];
UIBarButtonItem *rightBtnItem1 = [[UIBarButtonItem alloc]initWithImage:img style:UIBarButtonItemStylePlain target:self action:@selector(rightButtonItemClicked:)];
UIBarButtonItem *rightBtnItem2 = [[UIBarButtonItem alloc]initWithImage:img style:UIBarButtonItemStylePlain target:self action:@selector(rightButtonItemClicked:)];
self.navigationItem.rightBarButtonItems = @[rightNegativeSpacer,rightBtnItem1,rightBtnItem2];
我挺喜欢这么用dispatch_group:
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,
0);dispatch_group_t group = dispatch_group_create();dispatch_group_async(group, queue, ^{//加入队列的block事件1;NSLog(@"block1开始执行");});dispatch_group_async(group, queue, ^{//加入队列的block事件2;NSLog(@"block2开始执行");});dispatch_group_notify(group, queue, ^{//block1和block2执行完成之后的押尾任务;NSLog(@"block1和block2都完成了");});
用云栖社区APP,舒服~
【云栖快讯】《阿里巴巴Java开发手册》(详尽版)已经上线!您的Java学好了吗?如果没有,那就赶紧加入学习吧!&&
移动测试(Mobile Testing)是为广大企业客户和移动开发者提供真机测试服务的云平台...
阿里云移动APP解决方案,助力开发者轻松应对移动app中随时可能出现的用户数量的爆发式增长、...
为您提供简单高效、处理能力可弹性伸缩的计算服务,帮助您快速构建更稳定、安全的应用,提升运维效...
云数据库HBase2.0产品发布会

我要回帖

更多关于 男生说不知道的含义 的文章

 

随机推荐