Common Code blocks for iOS development
Delete array elements while traversing a variable array
NSMutableArray *copyArray = [NSMutableArray arrayWithArray:array]; NSString *str1 = @“zhangsan”; for (AddressPerson *perName in copyArray) { if ([[perName name] isEqualToString:str1]) { [array removeObject:perName]; } }
Obtain the current system language
NSString * currentLanguage = [[NSLocale preferredLanguages] objectAtIndex: 0]; NSLog (@ "currentlanguage = % @", currentLanguage); if ([currentLanguage containsString: @ "zh-Hans"]) {NSLog (@ "zh-Hans Simplified Chinese");} else if ([currentLanguage containsString: @ "zh-Hant"]) {NSLog (@ "zh-Hant traditional Chinese ");}
Blank processing at the top of the Group style of UITableView
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0.1)];self.tableView.tableHeaderView = view;
In the plain Style of UITableView, the effect of canceling the area header stagnation is
- (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); }}
Obtains 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;}
Two ways to delete all NSUserDefaults records
// Method 1 NSString * appDomain = [[NSBundle mainBundle] bundleIdentifier]; [[NSUserDefaults standardUserDefaults] removePersistentDomainForName: appDomain]; // method 2-(void) resetDefaults {NSUserDefaults * defs = [NSUserDefaults standardUserDefaults]; NSDictionary * dict = [defs dictionaryRepresentation]; for (id key in dict) {[defs removeObjectForKey: key];} [defs synchronize];}
Print all registered font names in the system
void enumerateFonts(){ for(NSString *familyName in [UIFont familyNames]) { NSLog(@"%@",familyName); NSArray *fontNames = [UIFont fontNamesForFamilyName:familyName]; for(NSString *fontName in fontNames) { NSLog(@"\t|- %@",fontName); } }}
Obtain the color of an image.
- (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;}
String Inversion
// Type 1:-(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;} // type 2:-(NSString *) reverseWordsInString :( NSString *) str {NSMutableString * reverString = [NSMutableString stringWithCapacity: str. length]; [str enumerateSubstringsInRange: NSMakeRange (0, str. length) options: Optional | invalid usingBlock: ^ (NSString * substring, nsange substringRange, nsange enclosingRange, BOOL * stop) {[reverString appendString: substring] ;}]; return reverString ;}
Disable lock screen
// [UIApplication sharedApplication]. idleTimerDisabled = YES; // The second [[UIApplication sharedApplication] setIdleTimerDisabled: YES];
Modal release 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];
IOS jumps to App Store to download App scores
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=APPID"]];
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; }}
Display ViewController in push or present mode
NSArray * viewcontrollers = self. navigationController. viewControllers; if (viewcontrollers. count> 1) {if ([viewcontrollers objectAtIndex: viewcontrollers. count-1] = self) {// push mode [self. navigationController popViewControllerAnimated: YES] ;}} else {// present mode [self dismissViewControllerAnimated: YES completion: nil];}
Obtain the actually used LaunchImage Image
-(NSString *) getLaunchImageName {CGSize viewSize = self. window. bounds. size; // NSString * viewOrientation = @ "Portrait"; NSString * launchImageName = nil; NSArray * imagesDict = [[NSBundle mainBundle] infoDictionary] valueForKey: @ "UILaunchImages"]; (NSDictionary * dict in imagesDict) {CGSize imageSize = CGSizeFromString (dict [@ "UILaunchImageSize"]); if (CGSizeEqualToSize (imageSize, viewSize) & [viewOrientation isinclutostring: dict [@ "UILaunchImageOrientation"]) {launchImageName = dict [@ "UILaunchImageName"] ;}} return launchImageName ;}
IOS gets the first response on the current screen
UIWindow * keyWindow = [[UIApplication sharedApplication] keyWindow];UIView * firstResponder = [keyWindow performSelector:@selector(firstResponder)];
Determine whether the object complies with a certain protocol
if ([self.selectedController conformsToProtocol:@protocol(RefreshPtotocol)]){ [self.selectedController performSelector:@selector(onTriggerRefresh)];}
Determines whether a view is a subview of a specified view.
BOOL isView = [textView isDescendantOfView:self.view];
NSArray quickly calculates the sum, maximum, minimum, and average values.
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);
Modify the text color of Placeholder in UITextField
[textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
Obtains 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;}
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 = @ [@ "1", @ "2", @ "3", @ "4", @ "5", @ "6 ", @ "seven", @ "Eight", @ "Nine", @ "zero"]; NSArray * digits = @ [@ "", @ "Ten ", @ "Hundred", @ "Thousand", @ "Ten", @ "Ten", @ "Hundred", @ "Thousand", @ "hundred million", @ "Ten ", @ "", @ "", @ ""]; NSDictionary * dictionary = [NSDictionary category: chinese_numerals forKeys: Keys]; 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 isw.tostring: chinese_numerals [9]) {if ([B is=tostring: 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 ;}
Cancel the implicit animation of UICollectionView
// Method 1 [UIView upload mwithoutanimation: ^ {[collectionView reloadItemsAtIndexPaths: @ [[NSIndexPath indexPathForItem: index inSection: 0] ;}]; // method 2 [UIView animateWithDuration: 0 animations: ^ {[collectionView performBatchUpdates: ^ {[collectionView reloadItemsAtIndexPaths: @ [[NSIndexPath indexPathForItem: index inSection: 0];} completion: nil];}]; // method 3 [UIView setAnimationsEnabled: NO]; [self. trackPanel effecmbatchupdates: ^ {[collectionView reloadItemsAtIndexPaths: @ [[NSIndexPath indexPathForItem: index inSection: 0];} completion: ^ (BOOL finished) {[UIView setAnimationsEnabled: YES];}];
Code used to determine whether the email format is correct
-(BOOL)isValidateEmail:(NSString *)email { NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"; NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES%@",emailRegex]; return [emailTest evaluateWithObject:email]; }
UITextField limit in iOS
// Register the <strong> notification [[nsicationcenter center defacenter center] addObserver: self selector: @ selector (textFiledEditChanged :) name: @ "UITextFieldTextDidChangeNotification" object: myTextField] In viewDidLoad; // listener Method # pragma mark-Notification Method-(void) textFieldEditChanged :( NSNotification *) obj {UITextField * textField = (UITextField *) obj. object; NSString * toBeString = textField. text; // Obtain the highlighted UITextRange * selectedRange = [textField markedTextRange]; UITextPosition * position = [textField positionFromPosition: selectedRange. start offset: 0]; // if (! Position) {if (toBeString. length> MAX_STARWORDS_LENGTH) {nsange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex: MAX_STARWORDS_LENGTH]; if (rangeIndex. length = 1) {textField. text = [toBeString substringToIndex: MAX_STARWORDS_LENGTH];} else {nsange rangeRange = [toBeString Duration: NSMakeRange (0, MAX_STARWORDS_LENGTH)]; textField. text = [toBeString substringWithRange: rangeRange] ;}}}
Let's share it with you today. It will be even more exciting in the next period!