Here is a summary of some iOS development tips, can greatly facilitate our development, continuous update.
UITableView’s Group style handles top whitespace
Add the following code in viewWillAppear: / / grouping list head blank processing CGRect frame = myTableView. TableHeaderView. Frame; Frame. The size. Height = 0.1; UIView *headerView = [[UIView alloc] initWithFrame:frame]; [myTableView setTableHeaderView:headerView];Copy the code
In the plain style of UITableView, the header stasis effect is removed
- (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);
}
else if(scrollView.contentOffset.y>=sectionHeaderHeight)
{
scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
}
}Copy the code
Well, actually, let’s use the Group style haha.
Gets the controller of a 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;
}Copy the code
There are two ways to delete all NSUserDefaults records
// NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier]; [[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain]; Void setDefaults {NSUserDefaults * defs = [NSUserDefaults * defs]; NSDictionary * dict = [defs dictionaryRepresentation]; for (id key in dict) { [defs removeObjectForKey:key]; } [defs synchronize]; }Copy the code
Prints the names of all registered fonts in the system
#pragma mark - Print the names of all fonts in the system. #pragma mark - print the names of all fonts in the system. NSLog(@"%@",familyName); NSArray *fontNames = [UIFont fontNamesForFamilyName:familyName]; for(NSString *fontName in fontNames) { NSLog(@"\t|- %@",fontName); }}}Copy the code
Gets the color of a point in the picture
- (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 the 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; }Copy the code
String inversion
The first: - (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; } // Second type: - (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; }Copy the code
No screen lock,
By default, iOS locks the screen when the device hasn’t touched for a while. But there are some apps that don’t require a lock screen, like video players.
[UIApplication sharedApplication].idleTimerDisabled = YES; Or [[UIApplication sharedApplication] setIdleTimerDisabled: YES];Copy the code
Modal out transparent interface
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];Copy the code
Xcode debugging does not show memory footprint
There's an option in editSCheme called Enable Zoombie Objects deselect itCopy the code
Show hidden files
AppleShowAllFiles -bool true killall Finder // Hide defaults Write com.apple.finder AppleShowAllFiles -bool false killall FinderCopy the code
The string is divided by multiple symbols
image.png
IOS jump to the App Store to download App ratings
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=A PPID"]];Copy the code
IOS gets the pinyin of Chinese characters
+ (NSString *)transform:(NSString *) Chinese {// transform NSString to NSMutableString NSMutableString *pinyin = [Chinese mutableCopy]; / / convert Chinese characters to pinyin (with the phonetic symbol) CFStringTransform ((__bridge CFMutableStringRef) pinyin, NULL, kCFStringTransformMandarinLatin, NO); NSLog(@"%@", pinyin); / / remove the pinyin phonetic CFStringTransform (__bridge CFMutableStringRef) pinyin, NULL, kCFStringTransformStripCombiningMarks, NO); NSLog(@"%@", pinyin); Return pinyin; }Copy the code
Manually change the color of the iOS status bar
- (void)setStatusBarBackgroundColor:(UIColor *)color { UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"]; if ([statusBar respondsToSelector:@selector(setBackgroundColor:)]) { statusBar.backgroundColor = color; }}Copy the code
Determine whether the current ViewController is presented or pushed
NSArray *viewcontrollers=self.navigationController.viewControllers; If (viewcontrollers. Count > 1) {if ([viewcontrollers objectAtIndex: viewcontrollers. Count - 1] = = self) {/ / push way [self.navigationController popViewControllerAnimated:YES]; }} else {/ / the present way [self dismissViewControllerAnimated: YES completion: nil]; }Copy the code
Get the LaunchImage in action
- (NSString *)getLaunchImageName { CGSize viewSize = self.window.bounds.size; // Portrait 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 launchImageName; }Copy the code
IOS gets the first response on the current screen
UIWindow * keyWindow = [[UIApplication sharedApplication] keyWindow];
UIView * firstResponder = [keyWindow performSelector:@selector(firstResponder)];Copy the code
Determines whether an object complies with a protocol
if ([self.selectedController conformsToProtocol:@protocol(RefreshPtotocol)])
{
[self.selectedController performSelector:@selector(onTriggerRefresh)];
}Copy the code
Checks whether the view is a child of the specified view
BOOL isView = [textView isDescendantOfView:self.view];Copy the code
NSArray quickly calculates the maximum, minimum and average sum
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);Copy the code
Modify UITextField Placeholder text color
[textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];Copy the code
About the format of NSDateFormatter
For example, AD AD YY: the last two digits of the year YYYY: full year MM: month, displayed as 1-12 MM: month, displayed as the full name of the Month, such as Jan MMMM: month, displayed as the full name of the month, such as Janualy DD: day, represented by two digits, such as 02 D: Day, 1-2 bits display, such as 2 EEE: short day of the week, such as Sun EEEE: full day of the week, such as Sunday AA: morning and afternoon, AM/PM H: hour, 24-hour system, 0-23 K: hour, 12-hour system, 0-11 m: minute, 1-2 bits mm: minute, 2 bits S: S, 1-2 bits SS: S, 2 bits S: msCopy the code
Gets all subclasses of a class
+ (NSArray *) allSubclasses { Class myClass = [self class]; NSMutableArray *mySubclasses = [NSMutableArray array]; 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) { [mySubclasses addObject: classes[ci]]; } } free(classes); return mySubclasses; }Copy the code
CFNetwork. Framework is required to check whether an IOS device is configured with an agent
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 *) kCFProxyTypeNone] isEqualToString:@"kCFProxyTypeNone"]) {NSLog(@" no proxy "); } else {NSLog(@" set proxy "); }Copy the code
Convert Arabic numerals to Chinese format
+(NSString *)translation:(NSString *)arebic { NSString *str = arebic; NSArray *arabic_numerals = @[@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"0"]; NSArray * chinese_numerals = @ [@ "a," @ "second," @ "three," @ "four," @ "five," @ "six," @ "seven," @ "eight," @ "nine," @ "zero"]. NSArray * who = @ [@ "a," @ "ten," @ "best," @ "thousand" @ "wan", @ "ten," @ "best," @ "thousand" @ "$", @" ten, "@" best, "@" thousand ", @ "mega"]. 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]]) { 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); return chinese; }Copy the code
Base64 encoding converts to NSString or NSData objects
// 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);Copy the code
Unanimate implicit UICollectionView
By default, UICollectionView appends an implicit fade to reloadItems, which can be annoying, especially if your cell is a compound cell (e.g., the cell uses UIStackView). There are several ways to remove these animations
[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]; }];Copy the code
Have Xcode’s console support llDB-type printing
Open the terminal and enter three commands: touch ~/.lldbinit echo display @import UIKit >> ~/.lldbinit echo target stop-hook add -o \"target stop-hook disable\" >> ~/.lldbinitCopy the code
CocoaPods pod install/ POD update Update is slow
Pod install --verbose --no-repo-update pod update --verbose --no-repo-update Pod update --verbose --no-repo-update Adding a parameter can eliminate this step, and speed up quite a bitCopy the code
How much memory UIImage occupies
UIImage *image = [UIImage imageNamed:@"aa"];
NSUInteger size = CGImageGetHeight(image.CGImage) * CGImageGetBytesPerRow(image.CGImage);Copy the code
GCD timer Indicates the 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, ^{//@" countdown ends, close "dispatch_source_cancel(timer); dispatch_async(dispatch_get_main_queue(), ^{ }); }); dispatch_resume(timer);Copy the code
Draw text on the image and write a UIImage category
- (UIImage *)imageWithTitle:(NSString *)title fontSize:(CGFloat)fontSize {// canvas size CGSize size=CGSizeMake(self.size.width,self.size.height); / / create a context based on bitmap UIGraphicsBeginImageContextWithOptions (size, NO, 0.0); / / opaque: NO scale: 0.0 [self drawAtPoint: CGPointMake (0.0, 0.0)]. NSMutableParagraphStyle* paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy]; paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping; paragraphStyle.alignment=NSTextAlignmentCenter; Centered text / / / / computing the size of the text, the text centered on the canvas CGSize sizeText = [title boundingRectWithSize: self. The 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); // draw text [title drawInRect:rect withAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:fontSize],NSForegroundColorAttributeName:[ UIColor whiteColor],NSParagraphStyleAttributeName:paragraphStyle}]; / / return draw new graphics UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext (); UIGraphicsEndImageContext(); return newImage; }Copy the code
Find all child views of a view
- (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]];
}
}
return array;
}Copy the code
Calculate file size
// file size - (long long)fileSizeAtPath:(NSString *)path {NSFileManager *fileManager = [NSFileManager defaultManager]; if ([fileManager fileExistsAtPath:path]) { long long size = [fileManager attributesOfItemAtPath:path error:nil].fileSize; return size; } return 0; } // folder size - (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 += size; } } } return folderSize; }Copy the code
UIView sets partial rounded corners
Have you ever encountered such a problem, a button or a label, as long as the right corner of the two rounded, or only one rounded corner. What to do. This is where layer masks come in
CGRect rect = view.bounds; CGSize radio = CGSizeMake(30, 30); / / fillet dimension UIRectCorner corner = UIRectCornerTopLeft | UIRectCornerTopRight; / / this position only rounded UIBezierPath * path = [UIBezierPath bezierPathWithRoundedRect: the rect byRoundingCorners: corner cornerRadii: radio]; CAShapeLayer *masklayer = [[CAShapeLayer alloc]init]; // create shapelayer masklayer.frame = view.bounds; masklayer.path = path.CGPath; // Set path view.layer.mask = masklayer;Copy the code
Take up and take down
Floor(x), sometimes called floor(x), has the function of "rounding down", that is, taking the largest integer not greater than x for example: x=3.14, floor(x)=3, y=9.99999, floor(y)=9 Corresponds to the ceil function, that is, rounding up function. The purpose of the ceil function is to find the smallest integer not less than a given real number. Both the floor and ceil functions return doubleCopy the code
To calculate the length of a string, one Chinese character counts as two characters
- (int)convertToInt:(NSString*)strtemp {int strlength = 0; char* p = (char*)[strtemp cStringUsingEncoding:NSUnicodeStringEncoding]; for (int i=0 ; i<[strtemp lengthOfBytesUsingEncoding:NSUnicodeStringEncoding] ; i++) { if (*p) { p++; strlength++; } else { p++; } } return strlength; } // method 2: -(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 asciiLength; }Copy the code
Set an image for 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);Copy the code
Prevents scrollView gestures from overwriting sideslip gestures
[scrollView.panGestureRecognizerrequireGestureRecognizerToFail:self.navigationController.interactivePopGestureRecognizer ];Copy the code
Remove the back title returned from the navigation bar
[[UIBarButtonItemappearance]setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60)forBarMetrics:UIBarMetricsDefault];Copy the code
Whether the string contains Chinese characters
+ (BOOL)checkIsChinese:(NSString *)string
{
for (int i=0; iCopy the code
The use of 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(@" first request completed "); 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(@" Second request completed "); dispatch_group_leave(dispatchGroup); }); Dispatch_group_notify (dispatchGroup, dispatch_get_main_queue(), ^(){NSLog(@" request done "); });Copy the code
UITextField with a space for every four digits to implement proxy
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {// four bits plus one space if ([string isEqualToString:@""]) {// Delete character if ((textField.text.length - 2) % 5 == 0) { textField.text = [textField.text substringToIndex:textField.text.length - 1]; } return YES; } else { if (textField.text.length % 5 == 0) { textField.text = [NSString stringWithFormat:@"%@ ", textField.text]; } } return YES; }Copy the code
Get private attributes and member variables #import
- (void)setTextColor {// Get all the attributes to see if there are any corresponding attributes unsigned int count = 0; objc_property_t *propertys = class_copyPropertyList([UIDatePicker class], &count); for(int i = 0; i < count; I ++) {// Get each property objc_property_t property = propertys[I]; / / get the corresponding nsstrings nsstrings * propertyName = [nsstrings stringWithCString: property_getName (property) encoding:NSUTF8StringEncoding]; // Print the corresponding property NSLog(@" propertyName = %@",propertyName); if ([propertyName isEqualToString:@"textColor"]) { [datePicker setValue:[UIColor whiteColor] forKey:propertyName]; }}}Copy the code
// Get member variables such as UIAlertAction button font color unsigned int count = 0; Ivar *ivars = class_copyIvarList([UIAlertAction class], &count); for(int i =0; i < count; 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"]; }}Copy the code
Get the apps installed on your phone
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(@"bundleIdentifier")]);
NSLog(@"%@",[item performSelector:NSSelectorFromString(@"bundleVersion")]);
NSLog(@"%@",[item performSelector:NSSelectorFromString(@"shortVersionString")]);
}Copy the code
Determine if both dates are in the category of NSDate in the same week
- (BOOL) isSameDateWithDate date: (NSDate *) {/ / date interval between return NO more than seven days if (fabs ([self timeIntervalSinceDate: date]) > = 7 * 24 *3600) { return NO; } NSCalendar *calender = [NSCalendar currentCalendar]; calender.firstWeekday = 2; / / set the first day of a week starting Monday / / computing two dates this year how many weeks respectively NSUInteger countSelf = [calender ordinalityOfUnit: NSCalendarUnitWeekday inUnit:NSCalendarUnitYear forDate:self]; NSUInteger countDate = [calender ordinalityOfUnit:NSCalendarUnitWeekday inUnit:NSCalendarUnitYear forDate:date]; Return countSelf == countDate; }Copy the code
Open the system setting screen in the application
/ / after iOS8 [[UIApplication sharedApplication] openURL: [NSURL URLWithString: UIApplicationOpenSettingsURLString]]. // If the App does not add permissions, the setting interface is displayed. If the App has added permissions (such as notifications), the App Settings screen is displayed.Copy the code
// Before iOS8 // add a url type as shown in the figure below. [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=WIFI"]]; Possible values are as follows: The About - prefs: root = General&path = About the org.eclipse.swt.accessibility - prefs: root = General&path = the org.eclipse.swt.accessibility Airplane Mode On - Prefs :root=AIRPLANE_MODE auto-lock -- prefs:root=General&path=AUTOLOCK -- 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 = which wi-fi - prefs: root = WIFICopy the code
Image.png
The animation pauses and starts again
-(void)pauseLayer:(CALayer *)layer { CFTimeInterval pausedTime = [layer convertTime:CACurrentMediaTime() fromLayer:nil]; Layer. Speed = 0.0; layer.timeOffset = pausedTime; } -(void)resumeLayer:(CALayer *)layer { CFTimeInterval pausedTime = [layer timeOffset]; Layer. Speed = 1.0; Layer. The timeOffset = 0.0; Layer. BeginTime = 0.0; CFTimeInterval timeSincePause = [layer convertTime:CACurrentMediaTime() fromLayer:nil] - pausedTime; layer.beginTime = timeSincePause; }Copy the code
FillRule principle
Image.png
Number formatting in iOS
// With NSNumberFormatter, you can also set the format of the NSNumber output. For example: NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init]; formatter.numberStyle = NSNumberFormatterDecimalStyle; NSString *string = [formatter stringFromNumber:[NSNumber numberWithInt:123456789]]; NSLog(@"Formatted number string:%@",string); Formatted string: 1223:403 Formatted number string:123,456,789 Formatted number: [1223:403] Formatted number string:123,456,789 Formatted number string:123,456,789 Formatted number: [1223:403] Formatted number string:123,456,789 This enumeration includes: typedef NS_ENUM(NSUInteger, NSNumberFormatterStyle) { NSNumberFormatterNoStyle = kCFNumberFormatterNoStyle, NSNumberFormatterDecimalStyle = kCFNumberFormatterDecimalStyle, NSNumberFormatterCurrencyStyle = kCFNumberFormatterCurrencyStyle, NSNumberFormatterPercentStyle = kCFNumberFormatterPercentStyle, NSNumberFormatterScientificStyle = kCFNumberFormatterScientificStyle, NSNumberFormatterSpellOutStyle = kCFNumberFormatterSpellOutStyle }; // The effect of each enumeration on the output numeric format is as follows: the output of the third and last items varies according to the locale set by the system. [1243:403] Blank number :123,456,789 [1243:403 [1243:403] Formatted number string:1.23456789E8 [1243:403] 12three hundred and forty-five thousand six thousand seven hundred and eighty-nineCopy the code
How to get all WebView image addresses,
When the web page is loaded, the image is obtained through JS and the recognition mode of click is added
//UIWebView - (void)webViewDidFinishLoad:(UIWebView *)webView { Static NSString * const jsGetImages = @"function getImages(){\ var objs = document.getElementsByTagName(\"img\"); \ var imgScr = ''; \ for(var i=0; iCopy the code
//WKWebView - (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation { static NSString * const jsGetImages = @"function getImages(){\ var objs = document.getElementsByTagName(\"img\"); \ var imgScr = ''; \ for(var i=0; iCopy the code
Gets the webView height
CGFloat height = [[self.webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] floatValue];Copy the code
NavigationBar becomes pure transparent
/ / / / the first one navigation pure transparent [self. The navigationBar setBackgroundImage: [UIImage new] forBarMetrics: UIBarMetricsDefault]; / / remove the navigation bar at the bottom of the black line self. The navigationBar. ShadowImage = [UIImage new]; [[self.navigationBar subviews] objectAtIndex:0]. Alpha = 0;Copy the code
TabBar similarly
[self.tabBar setBackgroundImage:[UIImage new]];
self.tabBar.shadowImage = [UIImage new];Copy the code
NavigationBar is implemented according to the gradient of the sliding distance
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {CGFloat offsetToShow = 200.0; Slide / / how much is completely show CGFloat alpha = 1 - (offsetToShow - scrollView. ContentOffset. Y)/offsetToShow; [[self.navigationController.navigationBar subviews] objectAtIndex:0].alpha = alpha; }Copy the code
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {CGFloat offsetToShow = 200.0; CGFloat alpha = 1 - (offsetToShow - scrollView.contentOffset.y) / offsetToShow; [self.navigationController.navigationBar setShadowImage:[UIImage new]]; [self.navigationController.navigationBar setBackgroundImage:[self imageWithColor:[[UIColor orangeColor]colorWithAlphaComponent:alpha]] forBarMetrics:UIBarMetricsDefault]; } // create a solid color image - (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 theImage; }Copy the code
Some related paths in iOS development
The location of the simulator: / Applications/Xcode. App/Contents/Developer/Platforms/iPhoneSimulator platform/Developer/SDKs document installation location: / Applications/Xcode. App/Contents/Developer/Documentation/DocSets plug-in save the path: ~ / Library/ApplicationSupport/Developer/Shared/Xcode/plug-ins custom code save the path: ~ / Library/Developer/Xcode/UserData/CodeSnippets/if you can't find CodeSnippets folder, can create a new CodeSnippets folder. Description file path ~ / Library/MobileDevice/Provisioning ProfilesCopy the code
NavigationItem's BarButtonItem is adjacent to the right or left edge of the screen.
In general, items on the right are kept at a distance from the right side of the screen:
image.png
The following is done by adding a fixed spacing item with a negative width, or changing the width to achieve different spacing:
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];Copy the code
image.png