UITableView的Group样式下顶部空白处理
//分组列表头部空白处理UIView*view = [[UIViewalloc] initWithFrame:CGRectMake(0,0,0,0.1)];self.tableView.tableHeaderView= view;
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{ CGFloat sectionHeaderHeight = sectionHead.height;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); }}
那个,其实,还是用Group样式吧哈哈。
- (UIViewController*)viewController{UIViewController*viewController =nil;UIResponder*next=self.nextResponder;while(next) {if([nextisKindOfClass:[UIViewControllerclass]]){ viewController = (UIViewController*)next;break; }next=next.nextResponder; }returnviewController;}
//方法一NSString*appDomain = [[NSBundlemainBundle] bundleIdentifier];[[NSUserDefaultsstandardUserDefaults] removePersistentDomainForName:appDomain];//方法二- (void)resetDefaults{NSUserDefaults* defs = [NSUserDefaultsstandardUserDefaults];NSDictionary* dict = [defs dictionaryRepresentation];for(idkeyindict) { [defs removeObjectForKey:key]; } [defs synchronize];}
#pragma mark - 打印系统所有已注册的字体名称voidenumerateFonts(){for(NSString*familyNamein[UIFontfamilyNames]) {NSLog(@"%@",familyName);NSArray*fontNames = [UIFontfontNamesForFamilyName:familyName];for(NSString*fontNameinfontNames) {NSLog(@"\t|- %@",fontName); } }}
- (UIColor*) getPixelColorAtLocation:(CGPoint)point inImage:(UIImage*)image{UIColor* color =nil;CGImageRefinImage = image.CGImage;CGContextRefcgctx = [selfcreateARGBBitmapContextFromImage:inImage];if(cgctx ==NULL) {returnnil;/* error */} size_t w =CGImageGetWidth(inImage); size_t h =CGImageGetHeight(inImage);CGRectrect = {{0,0},{w,h}};CGContextDrawImage(cgctx, rect, inImage);unsignedchar* data =CGBitmapContextGetData(cgctx);if(data !=NULL) {intoffset =4*((w*round(point.y))+round(point.x));intalpha = data[offset];intred = data[offset+1];intgreen = data[offset+2];intblue = data[offset+3]; color = [UIColorcolorWithRed:(red/255.0f) green:(green/255.0f) blue: (blue/255.0f) alpha:(alpha/255.0f)]; }CGContextRelease(cgctx);if(data) { free(data); }returncolor;}
第一种:- (NSString*)reverseWordsInString:(NSString*)str{NSMutableString*newString = [[NSMutableStringalloc] initWithCapacity:str.length];for(NSIntegeri = str.length-1; i >=0; i --) {unicharch = [str characterAtIndex:i]; [newString appendFormat:@"%c", ch]; }returnnewString;}//第二种:- (NSString*)reverseWordsInString:(NSString*)str{NSMutableString*reverString = [NSMutableStringstringWithCapacity:str.length]; [str enumerateSubstringsInRange:NSMakeRange(0, str.length) options:NSStringEnumerationReverse|NSStringEnumerationByComposedCharacterSequencesusingBlock:^(NSString*substring,NSRangesubstringRange,NSRangeenclosingRange,BOOL*stop) { [reverString appendString:substring]; }];returnreverString;}
默认情况下,当设备一段时间没有触控动作时,iOS会锁住屏幕。但有一些应用是不需要锁屏的,比如视频播放器。
[UIApplicationsharedApplication].idleTimerDisabled=YES;或[[UIApplicationsharedApplication] setIdleTimerDisabled:YES];
UIViewController*vc = [[UIViewControlleralloc] init];UINavigationController*na = [[UINavigationControlleralloc] initWithRootViewController:vc];if([[[UIDevicecurrentDevice] systemVersion] floatValue] >=8.0){ na.modalPresentationStyle=UIModalPresentationOverCurrentContext;}else{self.modalPresentationStyle=UIModalPresentationCurrentContext;}[selfpresentViewController:na animated:YEScompletion:nil];
editSCheme 里面有个选项叫叫做enablezoombie Objects 取消选中
//显示defaults write com.apple.finderAppleShowAllFiles -booltruekillall Finder//隐藏defaults write com.apple.finderAppleShowAllFiles -boolfalsekillall Finder
image.png
[[UIApplication sharedApplication]openURL:[NSURL URLWithString:@"itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=APPID"]];
+ (NSString*)transform:(NSString*)chinese{//将NSString装换成NSMutableStringNSMutableString*pinyin = [chinese mutableCopy];//将汉字转换为拼音(带音标)CFStringTransform((__bridgeCFMutableStringRef)pinyin,NULL, kCFStringTransformMandarinLatin,NO);NSLog(@"%@", pinyin);//去掉拼音的音标CFStringTransform((__bridgeCFMutableStringRef)pinyin,NULL, kCFStringTransformStripCombiningMarks,NO);NSLog(@"%@", pinyin);//返回最近结果returnpinyin; }
- (void)setStatusBarBackgroundColor:(UIColor*)color{UIView*statusBar = [[[UIApplicationsharedApplication] 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.navigationControllerpopViewControllerAnimated:YES]; }}else{//present方式[selfdismissViewControllerAnimated:YEScompletion:nil];}
- (NSString*)getLaunchImageName{CGSizeviewSize =self.window.bounds.size;// 竖屏NSString*viewOrientation =@"Portrait";NSString*launchImageName =nil;NSArray* imagesDict = [[[NSBundlemainBundle] infoDictionary] valueForKey:@"UILaunchImages"];for(NSDictionary* dictinimagesDict) {CGSizeimageSize =CGSizeFromString(dict[@"UILaunchImageSize"]);if(CGSizeEqualToSize(imageSize, viewSize) && [viewOrientation isEqualToString:dict[@"UILaunchImageOrientation"]]) { launchImageName = dict[@"UILaunchImageName"]; } }returnlaunchImageName;}
UIWindow* keyWindow = [[UIApplicationsharedApplication] keyWindow];UIView* firstResponder = [keyWindow performSelector:@selector(firstResponder)];
if([self.selectedControllerconformsToProtocol:@protocol(RefreshPtotocol)]){ [self.selectedControllerperformSelector:@selector(onTriggerRefresh)];}
BOOLisView = [textView isDescendantOfView:self.view];
NSArray*array = [NSArrayarrayWithObjects:@"2.0",@"2.3",@"3.0",@"4.0",@"10",nil];CGFloatsum = [[array valueForKeyPath:@"@sum.floatValue"] floatValue];CGFloatavg = [[array valueForKeyPath:@"@avg.floatValue"] floatValue];CGFloatmax =[[array valueForKeyPath:@"@max.floatValue"] floatValue];CGFloatmin =[[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"];
G: 公元时代,例如AD公元yy: 年的后2位yyyy: 完整年MM: 月,显示为1-12MMM: 月,显示为英文月份简写,如 JanMMMM: 月,显示为英文月份全称,如 Janualydd: 日,2位数表示,如02d: 日,1-2位显示,如2EEE: 简写星期几,如SunEEEE: 全写星期几,如Sundayaa: 上下午,AM/PMH: 时,24小时制,0-23K:时,12小时制,0-11m: 分,1-2位mm: 分,2位s: 秒,1-2位ss: 秒,2位S: 毫秒
+ (NSArray*) allSubclasses{ Class myClass = [selfclass];NSMutableArray*mySubclasses = [NSMutableArrayarray];unsignedintnumOfClasses; Class *classes = objc_copyClassList(&numOfClasses;);for(unsignedintci =0; ci < numOfClasses; ci++) { Class superClass = classes[ci];do{ superClass = class_getSuperclass(superClass); }while(superClass && superClass != myClass);if(superClass) { [mySubclasses addObject: classes[ci]]; } } free(classes);returnmySubclasses;}
监测IOS设备是否设置了代理,需要CFNetwork.framework
NSDictionary*proxySettings = (__bridgeNSDictionary*)(CFNetworkCopySystemProxySettings());NSArray*proxies = (__bridgeNSArray*)(CFNetworkCopyProxiesForURL((__bridgeCFURLRef_Nonnull)([NSURLURLWithString:@"http://www.baidu.com"]), (__bridgeCFDictionaryRef_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 = [NSDictionarydictionaryWithObjects:chinese_numerals forKeys:arabic_numerals];NSMutableArray*sums = [NSMutableArrayarray];for(inti =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]]) { sum = b;if([[sums lastObject] isEqualToString:chinese_numerals[9]]) { [sums removeLastObject]; } }else{ sum = chinese_numerals[9]; }if([[sums lastObject] isEqualToString:sum]) {continue; } } [sums addObject:sum]; }NSString*sumStr = [sums componentsJoinedByString:@""];NSString*chinese = [sumStr substringToIndex:sumStr.length-1];NSLog(@"%@",str);NSLog(@"%@",chinese);returnchinese;}
Base64编码与NSString对象或NSData对象的转换
// Create NSData objectNSData*nsdata = [@"iOS Developer Tips encoded in Base64"dataUsingEncoding:NSUTF8StringEncoding];// Get NSString from NSData object in Base64NSString*base64Encoded = [nsdata base64EncodedStringWithOptions:0];// Print the Base64 encoded stringNSLog(@"Encoded: %@", base64Encoded);// Let's go the other way...// NSData from the Base64 encoded strNSData*nsdataFromBase64String = [[NSDataalloc] initWithBase64EncodedString:base64Encoded options:0];// Decoded NSString from the NSDataNSString*base64Decoded = [[NSStringalloc] initWithData:nsdataFromBase64String encoding:NSUTF8StringEncoding];NSLog(@"Decoded: %@", base64Decoded);
UICollectionView在reloadItems的时候,默认会附加一个隐式的fade动画,有时候很讨厌,尤其是当你的cell是复合cell的情况下(比如cell使用到了UIStackView)。
下面几种方法都可以帮你去除这些动画
//方法一[UIViewperformWithoutAnimation:^{ [collectionView reloadItemsAtIndexPaths:@[[NSIndexPathindexPathForItem:index inSection:0]]];}];//方法二[UIViewanimateWithDuration:0animations:^{ [collectionView performBatchUpdates:^{ [collectionView reloadItemsAtIndexPaths:@[[NSIndexPathindexPathForItem:index inSection:0]]]; } completion:nil];}];//方法三[UIViewsetAnimationsEnabled:NO];[self.trackPanelperformBatchUpdates:^{ [collectionView reloadItemsAtIndexPaths:@[[NSIndexPathindexPathForItem:index inSection:0]]];} completion:^(BOOLfinished) { [UIViewsetAnimationsEnabled:YES];}];
打开终端输入三条命令:touch ~/.lldbinitechodisplay @import UIKit >> ~/.lldbinitechotarget stop-hook add -o \"target stop-hook disable\" >> ~/.lldbinit
CocoaPods pod install/pod update更新慢的问题
podinstall--verbose --no-repo-updatepodupdate--verbose --no-repo-update如果不加后面的参数,默认会升级CocoaPods的spec仓库,加一个参数可以省略这一步,然后速度就会提升不少
UIImage*image = [UIImageimageNamed:@"aa"];NSUIntegersize =CGImageGetHeight(image.CGImage) *CGImageGetBytesPerRow(image.CGImage);
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(), ^{ });});dispatch_resume(timer);
- (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,0.0)];//文字居中显示在画布上NSMutableParagraphStyle* paragraphStyle = [[NSParagraphStyledefaultParagraphStyle] mutableCopy]; paragraphStyle.lineBreakMode=NSLineBreakByCharWrapping; paragraphStyle.alignment=NSTextAlignmentCenter;//文字居中//计算文字所占的size,文字居中显示在画布上CGSizesizeText=[title boundingRectWithSize:self.sizeoptions:NSStringDrawingUsesLineFragmentOriginattributes:@{NSFontAttributeName:[UIFontsystemFontOfSize: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:rect withAttributes:@{NSFontAttributeName:[UIFontsystemFontOfSize:fontSize],NSForegroundColorAttributeName:[UIColorwhiteColor],NSParagraphStyleAttributeName:paragraphStyle}];//返回绘制的新图形UIImage*newImage=UIGraphicsGetImageFromCurrentImageContext();UIGraphicsEndImageContext();returnnewImage;}
- (NSMutableArray*)allSubViewsForView:(UIView*)view{NSMutableArray*array = [NSMutableArrayarrayWithCapacity:0];for(UIView*subViewinview.subviews) { [array addObject:subView];if(subView.subviews.count>0) { [array addObjectsFromArray:[selfallSubViewsForView:subView]]; } }returnarray;}
//文件大小- (longlong)fileSizeAtPath:(NSString*)path{NSFileManager*fileManager = [NSFileManagerdefaultManager];if([fileManager fileExistsAtPath:path]) {longlongsize = [fileManager attributesOfItemAtPath:path error:nil].fileSize;returnsize; }return0;}//文件夹大小- (longlong)folderSizeAtPath:(NSString*)path{NSFileManager*fileManager = [NSFileManagerdefaultManager];longlongfolderSize =0;if([fileManager fileExistsAtPath:path]) {NSArray*childerFiles = [fileManager subpathsAtPath:path];for(NSString*fileNameinchilderFiles) {NSString*fileAbsolutePath = [path stringByAppendingPathComponent:fileName];if([fileManager fileExistsAtPath:fileAbsolutePath]) {longlongsize = [fileManager attributesOfItemAtPath:fileAbsolutePath error:nil].fileSize; folderSize += size; } } }returnfolderSize;}
你是不是也遇到过这样的问题,一个button或者label,只要右边的两个角圆角,或者只要一个圆角。该怎么办呢。这就需要图层蒙版来帮助我们了
CGRectrect = view.bounds;CGSizeradio =CGSizeMake(30,30);//圆角尺寸UIRectCornercorner =UIRectCornerTopLeft|UIRectCornerTopRight;//这只圆角位置UIBezierPath*path = [UIBezierPathbezierPathWithRoundedRect:rect byRoundingCorners:corner cornerRadii:radio];CAShapeLayer*masklayer = [[CAShapeLayeralloc]init];//创建shapelayermasklayer.frame= view.bounds;masklayer.path= path.CGPath;//设置路径view.layer.mask= masklayer;
floor(x),有时候也写做Floor(x),其功能是“下取整”,即取不大于x的最大整数 例如:x=3.14,floor(x)=3y=9.99999,floor(y)=9与floor函数对应的是ceil函数,即上取整函数。ceil函数的作用是求不小于给定实数的最小整数。ceil(2)=ceil(1.2)=cei(1.5)=2.00floor函数与ceil函数的返回值均为double型
//方法一:- (int)convertToInt:(NSString*)strtemp{intstrlength =0;char* p = (char*)[strtemp cStringUsingEncoding:NSUnicodeStringEncoding];for(inti=0; i<[strtemp lengthOfBytesUsingEncoding:NSUnicodeStringEncoding] ;i++) {if(*p) { p++; strlength++; }else{ p++; } }returnstrlength;}//方法二:-(NSUInteger) unicodeLengthOfString: (NSString*) text{NSUIntegerasciiLength =0;for(NSUIntegeri =0; i < text.length; i++) {unicharuc = [text characterAtIndex: i]; asciiLength += isascii(uc) ?1:2; }returnasciiLength;}
UIImage*image = [UIImageimageNamed:@"image"];self.MYView.layer.contents= (__bridgeid_Nullable)(image.CGImage);self.MYView.layer.contentsRect=CGRectMake(0,0,0.5,0.5);
[scrollView.panGestureRecognizerrequireGestureRecognizerToFail:self.navigationController.interactivePopGestureRecognizer];
[[UIBarButtonItemappearance]setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60)forBarMetrics:UIBarMetricsDefault];
+ (BOOL)checkIsChinese:(NSString *)string{for(inti=0; i
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(@"请求完成");});
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{// 四位加一个空格if([stringisEqualToString:@""]) {// 删除字符if((textField.text.length -2) %5==0) { textField.text = [textField.text substringToIndex:textField.text.length -1]; }returnYES; }else{if(textField.text.length %5==0) { textField.text = [NSString stringWithFormat:@"%@ ", textField.text]; } }returnYES;}
//获取私有属性 比如设置UIDatePicker的字体颜色- (void)setTextColor{//获取所有的属性,去查看有没有对应的属性unsignedintcount =0; objc_property_t *propertys = class_copyPropertyList([UIDatePickerclass], &count);for(inti =0;i < count;i ++) {//获得每一个属性objc_property_t property = propertys[i];//获得属性对应的nsstringNSString*propertyName = [NSStringstringWithCString:property_getName(property) encoding:NSUTF8StringEncoding];//输出打印看对应的属性NSLog(@"propertyname = %@",propertyName);if([propertyName isEqualToString:@"textColor"]) { [datePicker setValue:[UIColorwhiteColor] forKey:propertyName]; } }}
//获得成员变量 比如修改UIAlertAction的按钮字体颜色unsignedintcount =0; Ivar *ivars = class_copyIvarList([UIAlertActionclass], &count);for(inti =0;i < count;i ++) { Ivar ivar = ivars[i];NSString*ivarName = [NSStringstringWithCString:ivar_getName(ivar) encoding:NSUTF8StringEncoding];NSLog(@"uialertion.ivarName = %@",ivarName);if([ivarName isEqualToString:@"_titleTextColor"]) { [alertOk setValue:[UIColorblueColor] forKey:@"titleTextColor"]; [alertCancel setValue:[UIColorpurpleColor] forKey:@"titleTextColor"]; } }
Class c =NSClassFromString(@"LSApplicationWorkspace");ids = [(id)c performSelector:NSSelectorFromString(@"defaultWorkspace")];NSArray*array = [s performSelector:NSSelectorFromString(@"allInstalledApplications")];for(iditeminarray){NSLog(@"%@",[item performSelector:NSSelectorFromString(@"applicationIdentifier")]);//NSLog(@"%@",[item performSelector:NSSelectorFromString(@"bundleIdentifier")]);NSLog(@"%@",[item performSelector:NSSelectorFromString(@"bundleVersion")]);NSLog(@"%@",[item performSelector:NSSelectorFromString(@"shortVersionString")]);}
判断两个日期是否在同一周 写在NSDate的category里面
- (BOOL)isSameDateWithDate:(NSDate*)date{//日期间隔大于七天之间返回NOif(fabs([selftimeIntervalSinceDate:date]) >=7*24*3600) {returnNO; }NSCalendar*calender = [NSCalendarcurrentCalendar]; calender.firstWeekday=2;//设置每周第一天从周一开始//计算两个日期分别为这年第几周NSUIntegercountSelf = [calender ordinalityOfUnit:NSCalendarUnitWeekdayinUnit:NSCalendarUnitYearforDate:self];NSUIntegercountDate = [calender ordinalityOfUnit:NSCalendarUnitWeekdayinUnit:NSCalendarUnitYearforDate:date];//相等就在同一周,不相等就不在同一周returncountSelf == countDate;}
//iOS8之后[[UIApplicationsharedApplication] openURL:[NSURLURLWithString:UIApplicationOpenSettingsURLString]];//如果App没有添加权限,显示的是设定界面。如果App有添加权限(例如通知),显示的是App的设定界面。
//iOS8之前//先添加一个url type如下图,在代码中调用如下代码,即可跳转到设置页面的对应项[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=WIFI"]];可选值如下:About — prefs:root=General&path=AboutAccessibility — prefs:root=General&path=ACCESSIBILITYAirplane Mode On — prefs:root=AIRPLANE_MODEAuto-Lock— prefs:root=General&path=AUTOLOCKBrightness — prefs:root=BrightnessBluetooth — prefs:root=General&path=BluetoothDate&Time— prefs:root=General&path=DATE_AND_TIMEFaceTime — prefs:root=FACETIMEGeneral— prefs:root=GeneralKeyboard — prefs:root=General&path=KeyboardiCloud — prefs:root=CASTLEiCloudStorage&Backup— prefs:root=CASTLE&path=STORAGE_AND_BACKUPInternational — prefs:root=General&path=INTERNATIONALLocation Services — prefs:root=LOCATION_SERVICESMusic — prefs:root=MUSICMusic Equalizer — prefs:root=MUSIC&path=EQMusic VolumeLimit— prefs:root=MUSIC&path=VolumeLimitNetwork — prefs:root=General&path=NetworkNike + iPod — prefs:root=NIKE_PLUS_IPODNotes — prefs:root=NOTESNotification — prefs:root=NOTIFICATI*****_IDPhone — prefs:root=PhonePhotos — prefs:root=PhotosProfile — prefs:root=General&path=ManagedConfigurationListReset— prefs:root=General&path=ResetSafari — prefs:root=SafariSiri — prefs:root=General&path=AssistantSounds — prefs:root=SoundsSoftwareUpdate— prefs:root=General&path=SOFTWARE_UPDATE_LINKStore— prefs:root=STORETwitter — prefs:root=TWITTERUsage— prefs:root=General&path=USAGEVPN — prefs:root=General&path=Network/VPNWallpaper — prefs:root=WallpaperWi-Fi — prefs:root=WIFI
Image.png
-(void)pauseLayer:(CALayer*)layer{CFTimeIntervalpausedTime = [layer convertTime:CACurrentMediaTime() fromLayer:nil]; layer.speed=0.0; layer.timeOffset= pausedTime;}-(void)resumeLayer:(CALayer*)layer{CFTimeIntervalpausedTime = [layer timeOffset]; layer.speed=1.0; layer.timeOffset=0.0; layer.beginTime=0.0;CFTimeIntervaltimeSincePause = [layer convertTime:CACurrentMediaTime() fromLayer:nil] - pausedTime; layer.beginTime= timeSincePause;}
Image.png
//通过NSNumberFormatter,同样可以设置NSNumber输出的格式。例如如下代码:NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];formatter.numberStyle = NSNumberFormatterDecimalStyle;NSString *string= [formatter stringFromNumber:[NSNumber numberWithInt:123456789]];NSLog(@"Formatted number string:%@",string);//输出结果为:[1223:403] Formatted number string:123,456,789//其中NSNumberFormatter类有个属性numberStyle,它是一个枚举型,设置不同的值可以输出不同的数字格式。该枚举包括:typedefNS_ENUM(NSUInteger, NSNumberFormatterStyle){ NSNumberFormatterNoStyle = kCFNumberFormatterNoStyle, NSNumberFormatterDecimalStyle = kCFNumberFormatterDecimalStyle, NSNumberFormatterCurrencyStyle = kCFNumberFormatterCurrencyStyle, NSNumberFormatterPercentStyle = kCFNumberFormatterPercentStyle, NSNumberFormatterScientificStyle = kCFNumberFormatterScientificStyle, NSNumberFormatterSpellOutStyle = kCFNumberFormatterSpellOutStyle};//各个枚举对应输出数字格式的效果如下:其中第三项和最后一项的输出会根据系统设置的语言区域的不同而不同。[1243:403] Formatted numberstring:123456789[1243:403] Formatted numberstring:123,456,789[1243:403] Formatted numberstring:¥123,456,789.00[1243:403] Formatted numberstring:-539,222,988%[1243:403] Formatted numberstring:1.23456789E8[1243:403] Formatted numberstring:一亿二千三百四十五万六千七百八十九
在网页加载完成时,通过js获取图片和添加点击的识别方式
//UIWebView- (void)webViewDidFinishLoad:(UIWebView*)webView{//这里是js,主要目的实现对url的获取staticNSString*constjsGetImages =@"function getImages(){\
var objs = document.getElementsByTagName(\"img\");\
var imgScr = '';\
for(var i=0;i
imgScr = imgScr + objs[i].src + '+';\
};\
return imgScr;\
};"; [webView stringByEvaluatingJavaScriptFromString:jsGetImages];//注入js方法NSString*urlResult = [webView stringByEvaluatingJavaScriptFromString:@"getImages()"];NSArray*urlArray = [NSMutableArrayarrayWithArray:[urlResult componentsSeparatedByString:@"+"]];//urlResurlt 就是获取到得所有图片的url的拼接;mUrlArray就是所有Url的数组}
//WKWebView- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation{staticNSString*constjsGetImages =@"function getImages(){\
var objs = document.getElementsByTagName(\"img\");\
var imgScr = '';\
for(var i=0;i
imgScr = imgScr + objs[i].src + '+';\
};\
return imgScr;\
};"; [webView evaluateJavaScript:jsGetImages completionHandler:nil]; [webView evaluateJavaScript:@"getImages()"completionHandler:^(id_Nullable result,NSError* _Nullable error) {NSLog(@"%@",result); }];}
CGFloatheight = [[self.webViewstringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] floatValue];
//第一种方法//导航栏纯透明[self.navigationBarsetBackgroundImage:[UIImagenew] forBarMetrics:UIBarMetricsDefault];//去掉导航栏底部的黑线self.navigationBar.shadowImage= [UIImagenew];//第二种方法[[self.navigationBarsubviews] objectAtIndex:0].alpha=0;
[self.tabBarsetBackgroundImage:[UIImagenew]];self.tabBar.shadowImage= [UIImagenew];
//第一种- (void)scrollViewDidScroll:(UIScrollView*)scrollView{CGFloatoffsetToShow =200.0;//滑动多少就完全显示CGFloatalpha =1- (offsetToShow - scrollView.contentOffset.y) / offsetToShow; [[self.navigationController.navigationBarsubviews] objectAtIndex:0].alpha= alpha;}
//第二种- (void)scrollViewDidScroll:(UIScrollView*)scrollView{CGFloatoffsetToShow =200.0;CGFloatalpha =1- (offsetToShow - scrollView.contentOffset.y) / offsetToShow; [self.navigationController.navigationBarsetShadowImage:[UIImagenew]]; [self.navigationController.navigationBarsetBackgroundImage:[selfimageWithColor:[[UIColororangeColor]colorWithAlphaComponent:alpha]] forBarMetrics:UIBarMetricsDefault];}//生成一张纯色的图片- (UIImage*)imageWithColor:(UIColor*)color{CGRectrect =CGRectMake(0.0f,0.0f,1.0f,1.0f);UIGraphicsBeginImageContext(rect.size);CGContextRefcontext =UIGraphicsGetCurrentContext();CGContextSetFillColorWithColor(context, [colorCGColor]);CGContextFillRect(context, rect);UIImage*theImage =UIGraphicsGetImageFromCurrentImageContext();UIGraphicsEndImageContext();returntheImage;}
模拟器的位置:/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会和屏幕右侧保持一段距离:
image.png
下面是通过添加一个负值宽度的固定间距的item来解决,也可以改变宽度实现不同的间隔:
UIImage*img = [[UIImageimageNamed:@"icon_cog"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];//宽度为负数的固定间距的系统itemUIBarButtonItem*rightNegativeSpacer = [[UIBarButtonItemalloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpacetarget:nilaction:nil];[rightNegativeSpacer setWidth:-15];UIBarButtonItem*rightBtnItem1 = [[UIBarButtonItemalloc]initWithImage:img style:UIBarButtonItemStylePlaintarget:selfaction:@selector(rightButtonItemClicked:)];UIBarButtonItem*rightBtnItem2 = [[UIBarButtonItemalloc]initWithImage:img style:UIBarButtonItemStylePlaintarget:selfaction:@selector(rightButtonItemClicked:)];self.navigationItem.rightBarButtonItems= @[rightNegativeSpacer,rightBtnItem1,rightBtnItem2];
网友评论