iOS開發常用代碼塊(2),ios開發代碼

來源:互聯網
上載者:User

iOS開發常用代碼塊(2),ios開發代碼
GCD定時器

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 *)imageWithTitle:(NSString *)title fontSize:(CGFloat)fontSize{    //畫布大小    CGSize size=CGSizeMake(self.size.width,self.size.height);    //建立一個基於位元影像的上下文    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;//文字置中 //計算文字所佔的size,文字置中顯示在畫布上 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 newImage;}

 

尋找一個視圖的所有子視圖
- (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;}

 

計算檔案大小
//檔案大小- (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;}//檔案夾大小- (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;}

 

UIView的設定部分圓角
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];//建立shapelayermasklayer.frame = view.bounds;masklayer.path = path.CGPath;//設定路徑view.layer.mask = masklayer;

 

計算字串字元長度,一個漢字算兩個字元
//方法一:- (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;}//方法二:-(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;}

 

防止滾動視圖手勢覆蓋側滑手勢
[scrollView.panGestureRecognizer requireGestureRecognizerToFail:self.navigationController.interactivePopGestureRecognizer];

 

去掉導覽列返回的標題
[[UIBarButtonItem appearance]setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60)forBarMetrics:UIBarMetricsDefault];

 

字串中是否含有中文
+ (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;}

 

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;    }    else    {        if (textField.text.length % 5 == 0)        {            textField.text = [NSString stringWithFormat:@"%@ ", textField.text];        }    }    return YES;}

 

擷取手機安裝的應用
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")]);}

 

應用內開啟系統設定介面
//iOS8之後[[UIApplication sharedApplication] openURL:[NSURL URLWithString: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=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=SafariSiri — 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

 

動畫暫停再開始
-(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;}

 

iOS版中數位格式化
//通過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,它是一個枚舉型,設定不同的值可以輸出不同的數字格式。該枚舉包括:typedef NS_ENUM(NSUInteger, NSNumberFormatterStyle) {    NSNumberFormatterNoStyle = kCFNumberFormatterNoStyle,    NSNumberFormatterDecimalStyle = kCFNumberFormatterDecimalStyle,    NSNumberFormatterCurrencyStyle = kCFNumberFormatterCurrencyStyle,    NSNumberFormatterPercentStyle = kCFNumberFormatterPercentStyle,    NSNumberFormatterScientificStyle = kCFNumberFormatterScientificStyle,    NSNumberFormatterSpellOutStyle = kCFNumberFormatterSpellOutStyle};//各個枚舉對應輸出數字格式的效果如下:其中第三項和最後一項的輸出會根據系統設定的語言地區的不同而不同。[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:一億二千三百四十五萬六千七百八十九

 

如何擷取的WebView所有的圖片地址
//UIWebView- (void)webViewDidFinishLoad:(UIWebView *)webView{    //這裡是js,主要目的實現對url的擷取    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];//注入js方法    NSString *urlResult = [webView stringByEvaluatingJavaScriptFromString:@"getImages()"];    NSArray *urlArray = [NSMutableArray arrayWithArray:[urlResult componentsSeparatedByString:@"+"]];    //urlResurlt 就是擷取到得所有圖片的url的拼接;mUrlArray就是所有Url的數組}//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);    }];}

 

擷取到的WebView的高度
CGFloat height = [[self.webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] floatValue];

 

導覽列變為純透明
//第一種方法//導覽列純透明[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) / offsetToShow;    [[self.navigationController.navigationBar subviews] objectAtIndex:0].alpha = alpha;}//第二種- (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];}//產生一張純色的圖片- (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;}

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.