Common Code blocks for iOS development (2): ios development code

Source: Internet
Author: User

Common Code blocks for iOS development (2): ios development code
GCD Timer

Required queue = hour (hour, 0); dispatch_source_t timer = dispatch_source_create (hour, 0, 0, queue); hour (timer, dispatch_walltime (NULL, 0), 1.0 * NSEC_PER_SEC, 0); // execute the timer (timer, ^ {// The countdown ends. Disable dispatch_source_cancel (timer); dispatch_async (dispatch_get_main_queue (), ^ {});}); dispatch_resume (timer );

 

Draw text on the Image
-(UIImage *) imageWithTitle :( NSString *) title fontSize :( CGFloat) fontSize {// canvas size CGSize size = CGSizeMake (self. size. width, self. size. height); // create a bitmap-based context uigraphicsbeginimagecontextwittions (size, NO, 0.0); // opaque: NO scale: 0.0 [self drawAtPoint: CGPointMake (0.0, 0.0)]; // The text is displayed in the center of the canvas. NSMutableParagraphStyle * paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy]; paragraphStyle. lineBreakMode = NSLineBreakByCharWrapping;
ParagraphStyle. alignment = NSTextAlignmentCenter; // center the text. // calculate the size occupied by the text. The text is displayed in the center of the canvas 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); // draw the text [title drawInRect: rect withAttributes: @ {NSFontAttributeName: [UIFont systemFontOfSize: fontSize], identifier: [UIColor whiteColor], identifier: paragraphStyle}]; // return the newly drawn image UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext (); UIGraphicsEndImageContext (); return newImage ;}

 

Search for all subviews 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;}

 

Calculate the file size
// File size-(long) fileSizeAtPath :( NSString *) path {NSFileManager * fileManager = [NSFileManager defaultManager]; if ([fileManager fileExistsAtPath: path]) {long size = [fileManager attributesOfItemAtPath: path error: nil]. fileSize; return size;} return 0;} // folder size-(long) folderSizeAtPath :( NSString *) path {NSFileManager * fileManager = [NSFileManager defaultManager]; long folderSize = 0; if ([fileManager fileExistsAtPath: path]) {NSArray * childerFiles = [fileManager subpathsAtPath: path]; for (NSString * fileName in childerFiles) {NSString * fileAbsolutePath = [path paths: fileName]; if ([fileManager fileExistsAtPath: fileAbsolutePath]) {long size = [fileManager attributesOfItemAtPath: fileAbsolutePath error: nil]. fileSize; folderSize + = size ;}} return folderSize ;}

 

Set partial rounded corner of UIView
CGRect rect = view. bounds; CGSize radio = CGSizeMake (30, 30); // corner size UIRectCorner corner = UIRectCornerTopLeft | border; // UIBezierPath * path = [UIBezierPath direction: rect limit: corner cornerRadii: radio]; CAShapeLayer * masklayer = [[CAShapeLayer alloc] init]; // create shapelayermasklayer. frame = view. bounds; masklayer. path = path. CGPath; // set the path view. layer. mask = masklayer;

 

Calculates the length of a string. One Chinese character is counted as two characters.
// Method 1:-(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 ;}

 

Prevents the scrolling view gesture from overwriting the slide gesture
[scrollView.panGestureRecognizer requireGestureRecognizerToFail:self.navigationController.interactivePopGestureRecognizer];

 

Remove the title returned from the navigation bar
[[UIBarButtonItem appearance]setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60)forBarMetrics:UIBarMetricsDefault];

 

Whether the string contains Chinese Characters
+ (BOOL)checkIsChinese:(NSString *)string{    for (int i=0; i<string.length; i++)    {        unichar ch = [string characterAtIndex:i];        if (0x4E00 <= ch  && ch <= 0x9FA5)        {            return YES;        }    }    return NO;}

 

Use of dispatch_group
Required dispatchGroup = dispatch_group_create (); dispatch_group_enter (dispatchGroup); dispatch_after (dispatch_time (interval, (int64_t) (1 * NSEC_PER_SEC), interval (), ^ {NSLog (@ "the first request is completed"); then (dispatchGroup) ;}); dispatch_group_enter (dispatchGroup); dispatch_after (dispatch_time (DISPATCH_TIME_NOW, (int64_t) (10 * NSEC_PER_SEC), complete (), ^ {NSLog (@ "second request completed"); dispatch_group_leave (dispatchGroup) ;}); dispatch_group_policy (dispatchGroup, assign (), ^ () {NSLog (@ "request completed ");});

 

UITextField adds a space every four digits to implement proxy
-(BOOL) textField :( UITextField *) textField shouldChangeCharactersInRange :( nsange) range replacementString :( NSString *) string {// four digits add a space if ([string isw.tostring: @ ""]) {// Delete the 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 ;}

 

Get apps installed on mobile phones
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")]);}

 

Open the system settings page in the application.
// [[UIApplication sharedApplication] openURL: [NSURL URLWithString: UIApplicationOpenSettingsURLString] After iOS8; // If the App does not have the permission, the setting interface is displayed. If the App has the Add permission (for example, notification), the setting page of the App is displayed. // Before iOS8 // Add a url type and call the following code in the code to jump to the corresponding item [[UIApplication sharedApplication] openURL: [NSURL URLWithString: @ "prefs: root = WIFI"]; optional values: 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 = effecthdate & Time-prefs: root = General & path = DATE_AND_TIMEFaceTime-prefs: root = FACETIMEGeneral-prefs: root = GeneralKeyboard-prefs: root = General & path = KeyboardiCloud-prefs: root = CASTLEiCloud Storage & 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 Volume Limit-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 = policissiri-prefs: root = General & path = AssistantSounds-prefs: root = SoundsSoftware Update-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

 

Pause the animation and start 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.timeOffset = 0.0;    layer.beginTime = 0.0;    CFTimeInterval timeSincePause = [layer convertTime:CACurrentMediaTime() fromLayer:nil] - pausedTime;    layer.beginTime = timeSincePause;}

 

Number formatting in iOS
// You can also set the format of NSNumber output through NSNumberFormatter. For example, the following code: NSNumberFormatter * formatter = [[NSNumberFormatter alloc] init]; formatter. numberStyle = NSNumberFormatterDecimalStyle; NSString * string = [formatter stringFromNumber: [NSNumber numberWithInt: 123456789]; NSLog (@ "Formatted number string: % @", string ); // The output result is: [1223:403] Formatted number string: 123,456,789 // The NSNumberFormatter class has a property numberStyle, which is an enumeration type, you can set different values to output different numeric formats. This enumeration includes: typedef NS_ENUM (NSUInteger, NSNumberFormatterStyle) {NSNumberFormatterNoStyle = kCFNumberFormatterNoStyle, Signature = signature, Signature = signature, NSNumberFormatterPercentStyle = signature, Signature = delimiter, NSNumberFormatterSpellO UtStyle = kCFNumberFormatterSpellOutStyle}; // The output format of each enumeration is as follows: the output of the third and last entries varies depending on the language regions set by the system. [1243: 403] Formatted number string: 123456789 [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.23456789E8 [1243: 403] Formatted number string: 0.1 billion 23,456,789

 

How to obtain all the image addresses of the WebView
// UIWebView-(void) webViewDidFinishLoad :( UIWebView *) webView {// This is js. It is mainly used to obtain static NSString * const jsGetImages = @ "function getImages () {\ var objs = document. getElementsByTagName (\ "img \"); \ var imgScr = ''; \ for (var I = 0; I <objs. length; I ++) {\ imgScr = imgScr + objs [I]. src + ';\};\ return imgScr ;\}; "; [webView stringByEvaluatingJavaScriptFromString: jsGetImages]; // inject the js method NSString * urlResult = [webView progress: @ "getImages ()"]; NSArray * urlArray = [NSMutableArray arrayWithArray: [urlResult componentsSeparatedByString: @ "+"]; // urlResurlt is the splicing of the URLs of all images obtained; mUrlArray is the array of all URLs} // 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; I <objs. length; 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) ;}];}

 

Height of the obtained WebView
CGFloat height = [[self.webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] floatValue];

 

The navigation bar becomes transparent.
// Method 1 // The navigation bar is transparent [self. navigationBar setBackgroundImage: [UIImage new] forBarMetrics: UIBarMetricsDefault]; // remove the black line self at the bottom of the navigation bar. navigationBar. shadowImage = [UIImage new]; // method 2 [self. navigationBar subviews] objectAtIndex: 0]. alpha = 0;

 

TabBar becomes transparent
[self.tabBar setBackgroundImage:[UIImage new]];self.tabBar.shadowImage = [UIImage new];

 

NavigationBar Gradient Based on sliding distance
// First-(void) scrollViewDidScroll :( UIScrollView *) scrollView {CGFloat offsetToShow = 200.0; // when the number of slides is displayed, CGFloat alpha = 1-(offsetToShow-scrollView. contentOffset. y)/offsetToShow; [[self. navigationController. navigationBar subviews] objectAtIndex: 0]. alpha = alpha;} // type 2-(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 orientation: [self imageWithColor: [[UIColor orangeColor] colorWithAlphaComponent: alpha] forBarMetrics: UIBarMetricsDefault];} // generates 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 = Response (); Response (); return theImage ;}

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.