iOS開發小tip

西門吹霧發表於2018-04-17

RTL適配

www.cocoachina.com/ios/2018041…

UITableView的plain樣式下,取消區頭停滯效果

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat sectionHeaderHeight = sectionHead.height;
    if (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);
    }
}
複製程式碼

獲取某個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;
}
複製程式碼

兩種方法刪除NSUserDefaults所有記錄

//方法一
NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];
 
 
//方法二
- (void)resetDefaults
{
    NSUserDefaults * defs = [NSUserDefaults standardUserDefaults];
    NSDictionary * dict = [defs dictionaryRepresentation];
    for (id key in dict)
    {
        [defs removeObjectForKey:key];
    }
    [defs synchronize];
}
複製程式碼

取圖片某一畫素點的顏色 在UIImage的分類中

- (UIColor *)colorAtPixel:(CGPoint)point
{
    if (!CGRectContainsPoint(CGRectMake(0.0f, 0.0f, self.size.width, self.size.height), point))
    {
        return nil;
    }
 
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    int bytesPerPixel = 4;
    int bytesPerRow = bytesPerPixel * 1;
    NSUInteger bitsPerComponent = 8;
    unsigned char pixelData[4] = {0, 0, 0, 0};
 
    CGContextRef context = CGBitmapContextCreate(pixelData,
                                                 1,
                                                 1,
                                                 bitsPerComponent,
                                                 bytesPerRow,
                                                 colorSpace,
                                                 kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
    CGColorSpaceRelease(colorSpace);
    CGContextSetBlendMode(context, kCGBlendModeCopy);
 
    CGContextTranslateCTM(context, -point.x, point.y - self.size.height);
    CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, self.size.width, self.size.height), self.CGImage);
    CGContextRelease(context);
 
    CGFloat red   = (CGFloat)pixelData[0] / 255.0f;
    CGFloat green = (CGFloat)pixelData[1] / 255.0f;
    CGFloat blue  = (CGFloat)pixelData[2] / 255.0f;
    CGFloat alpha = (CGFloat)pixelData[3] / 255.0f;
 
    return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
}
複製程式碼

字串反轉

第一種:
- (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;
}
 
//第二種:
- (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;
}
複製程式碼

禁止鎖屏

[UIApplication sharedApplication].idleTimerDisabled = YES;
或
[[UIApplication sharedApplication] setIdleTimerDisabled:YES];

複製程式碼

iOS跳轉到App Store下載應用評分

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=APPID"]];
複製程式碼

手動更改iOS狀態列的顏色

- (void)setStatusBarBackgroundColor:(UIColor *)color
{
    UIView *statusBar = [[[UIApplication sharedApplication] 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.navigationController popViewControllerAnimated:YES];
    }
}
else
{
    //present方式
    [self dismissViewControllerAnimated:YES completion:nil];
}
獲取實際使用的LaunchImage圖片
 
- (NSString *)getLaunchImageName
{
    CGSize viewSize = self.window.bounds.size;
    // 豎屏    
    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;
}
複製程式碼

iOS在當前螢幕獲取第一響應

UIWindow * keyWindow = [[UIApplication sharedApplication] keyWindow];
UIView * firstResponder = [keyWindow performSelector:@selector(firstResponder)];
複製程式碼

判斷view是不是指定檢視的子檢視

BOOL isView = [textView isDescendantOfView:self.view];
複製程式碼

NSArray 快速求總和 最大值 最小值 和 平均值

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];
複製程式碼

修改UITextField中Placeholder的文字顏色

[textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
複製程式碼

獲取一個類的所有子類

+ (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;
}
複製程式碼

阿拉伯數字轉中文格式

+(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 = [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;
}
複製程式碼

圖片上繪製文字 寫一個UIImage的category

- (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;
}
複製程式碼

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];//建立shapelayer
masklayer.frame = view.bounds;
masklayer.path = path.CGPath;//設定路徑
view.layer.mask = masklayer;
複製程式碼

給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);
複製程式碼

防止scrollView手勢覆蓋側滑手勢

[scrollView.panGestureRecognizerrequireGestureRecognizerToFail:self.navigationController.interactivePopGestureRecognizer];
複製程式碼

去掉導航欄返回的back標題

[[UIBarButtonItem appearance]setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60)forBarMetrics:UIBarMetricsDefault];
複製程式碼

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;
}
複製程式碼

獲取私有屬性和成員變數 #import(objc/runtime.h)(由於系統原因此處用圓括號代替尖括號) //獲取私有屬性 比如設定UIDatePicker的字型顏色

- (void)setTextColor
{
    //獲取所有的屬性,去檢視有沒有對應的屬性
    unsigned int count = 0;
    objc_property_t *propertys = class_copyPropertyList([UIDatePicker class], &count);
    for(int i = 0;i ( count;i ++)
    {
        //獲得每一個屬性
        objc_property_t property = propertys[i];
        //獲得屬性對應的nsstring
        NSString *propertyName = [NSString stringWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
        //輸出列印看對應的屬性
        NSLog(@"propertyname = %@",propertyName);
        if ([propertyName isEqualToString:@"textColor"])
        {
            [datePicker setValue:[UIColor whiteColor] forKey:propertyName];
        }
    }
}
複製程式碼
//獲得成員變數 比如修改UIAlertAction的按鈕字型顏色
    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"];
        }
    }
複製程式碼

獲取手機安裝的應用

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")]);
}
複製程式碼

判斷兩個日期是否在同一周 寫在NSDate的category裡面

- (BOOL)isSameDateWithDate:(NSDate *)date
{
    //日期間隔大於七天之間返回NO
    if (fabs([self timeIntervalSinceDate:date]) >= 7 * 24 *3600)
    {
        return NO;
    }
 
    NSCalendar *calender = [NSCalendar currentCalendar];
    calender.firstWeekday = 2;//設定每週第一天從週一開始
    //計算兩個日期分別為這年第幾周
    NSUInteger countSelf = [calender ordinalityOfUnit:NSCalendarUnitWeekday inUnit:NSCalendarUnitYear forDate:self];
    NSUInteger countDate = [calender ordinalityOfUnit:NSCalendarUnitWeekday inUnit:NSCalendarUnitYear forDate:date];
 
    //相等就在同一周,不相等就不在同一周
    return countSelf == countDate;
}

複製程式碼

獲取到webview的高度

CGFloat height = [[self.webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] floatValue];
複製程式碼

navigationBar變為純透明

//第一種方法
//導航欄純透明
[self.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
//去掉導航欄底部的黑線
self.navigationBar.shadowImage = [UIImage new];
 
//第二種方法
[[self.navigationBar subviews] objectAtIndex:0].alpha = 0;
複製程式碼

//是否為同一天

+ (BOOL)isSameDay:(NSDate*)date1 date2:(NSDate*)date2
{
         NSCalendar* calendar = [NSCalendar currentCalendar];
    unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit;
    NSDateComponents* comp1 = [calendar components:unitFlags fromDate:date1];
    NSDateComponents* comp2 = [calendar components:unitFlags fromDate:date2];
     return [comp1 day] == [comp2 day] && [comp1 month] == [comp2 month] && [comp1 year]  == [comp2 year];
}
複製程式碼

通過新增一個負值寬度的固定間距的item來解決,也可以改變寬度實現不同的間隔:

UIImage *img = [[UIImage imageNamed:@"icon_cog"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
//寬度為負數的固定間距的系統item
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];
複製程式碼

修改textField的placeholder的字型顏色、大小

[self.textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
[self.textField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"];
複製程式碼

AFN移除JSON中的NSNull

AFJSONResponseSerializer *response = [AFJSONResponseSerializer serializer];
response.removesKeysWithNullValues = YES;
複製程式碼

NSString過濾特殊字元

// 定義一個特殊字元的集合
NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:
@"@/:;()¥「」"、[]{}#%-*+=_\\|~<>$€^•'@#$%^&*()_+'\""];
// 過濾字串的特殊字元
NSString *newString = [trimString stringByTrimmingCharactersInSet:set];
複製程式碼

去掉分割線多餘15畫素


首先在viewDidLoad方法加入以下程式碼:
 if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsZero];    
}   
 if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {        
        [self.tableView setLayoutMargins:UIEdgeInsetsZero];
}
然後在重寫willDisplayCell方法
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell 
forRowAtIndexPath:(NSIndexPath *)indexPath{   
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {       
             [cell setSeparatorInset:UIEdgeInsetsZero];    
    }    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {        
             [cell setLayoutMargins:UIEdgeInsetsZero];    
    }
}
複製程式碼

計算方法耗時時間間隔

// 獲取時間間隔
#define TICK   CFAbsoluteTime start = CFAbsoluteTimeGetCurrent();
#define TOCK   NSLog(@"Time: %f", CFAbsoluteTimeGetCurrent() - start)
複製程式碼

讓iOS應用直接退出

- (void)exitApplication {
    AppDelegate *app = [UIApplication sharedApplication].delegate;
    UIWindow *window = app.window;

    [UIView animateWithDuration:1.0f animations:^{
        window.alpha = 0;
    } completion:^(BOOL finished) {
        exit(0);
    }];
}
複製程式碼

Label行間距

-(void)test{
    NSMutableAttributedString *attributedString =    
   [[NSMutableAttributedString alloc] initWithString:self.contentLabel.text];
    NSMutableParagraphStyle *paragraphStyle =  [[NSMutableParagraphStyle alloc] init];  
   [paragraphStyle setLineSpacing:3];

    //調整行間距       
   [attributedString addAttribute:NSParagraphStyleAttributeName 
                         value:paragraphStyle 
                         range:NSMakeRange(0, [self.contentLabel.text length])];
     self.contentLabel.attributedText = attributedString;
}
複製程式碼

把tableview裡cell的小對勾的顏色改成別的顏色

_mTableView.tintColor = [UIColor redColor];
複製程式碼

螢幕截圖

   // 1. 開啟一個與圖片相關的圖形上下文
    UIGraphicsBeginImageContextWithOptions(self.view.bounds.size,NO,0.0);

    // 2. 獲取當前圖形上下文
    CGContextRef ctx = UIGraphicsGetCurrentContext();

    // 3. 獲取需要擷取的view的layer
    [self.view.layer renderInContext:ctx];

    // 4. 從當前上下文中獲取圖片
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

    // 5. 關閉圖形上下文
    UIGraphicsEndImageContext();

    // 6. 把圖片儲存到相簿
    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
複製程式碼

相關文章