iOS開發中一些比較實用的小方法

1.根據字體大小的計算出字符串的長和寬

  CGSize nameSize = [name sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:14],NSFontAttributeName, nil]];

2.通過生日計算年齡

//  calculate age by birthday
//  birthday : YYYYMMDD
//  age: *歲*個月*天
- (NSString *)ageStringByBirthday:(NSString *)birthday{
    //年齢計算
    NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
    [inputFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"] ] ;
    [inputFormatter setDateFormat:@"yyyyMMdd"];
    NSDate* inputDate = [inputFormatter dateFromString:birthday];
    
    
    NSDate *today = [NSDate date];
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    
    NSDateComponents *dayComponents = [gregorian components:NSCalendarUnitYear | NSCalendarUnitMonth| NSCalendarUnitDay fromDate:inputDate toDate:today options:0];
    
    long year = [dayComponents year];
    long month = [dayComponents month];
    long day = [dayComponents day];
    NSString *result = [NSString stringWithFormat:@"%li歲%li個月%li天",year,month,day];
    
    return result;
}

3.為右邊的導航按鈕設置彈簧距離

    UIButton* rightBtn= [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.titleLabel.font = [UIFont systemFontOfSize:11];
    [rightBtn setTitleColor:[UIColor colorWithRed:255.0/255 green:93.0/255 blue:93.0/255 alpha:1] forState:(UIControlStateNormal)];
    rightBtn.frame = CGRectMake(self.view.bounds.size.width-70, 20, 60, 44);
    
    UIBarButtonItem* rightBtnItem = [[UIBarButtonItem alloc]initWithCustomView:rightBtn];
    
    [rightBtn addTarget:self action:@selector(attentionBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *spaceItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:(UIBarButtonSystemItemFixedSpace) target:nil action:nil];
    spaceItem.width = -12;
    self.navigationItem.rightBarButtonItems = @[spaceItem, rightBtnItem];   

4.使得tableview在界面啟動后定位在某一行

 NSIndexPath *idxPath = [NSIndexPath indexPathForRow:5 inSection:0]; 
  [self.tableView scrollToRowAtIndexPath:idxPath  atScrollPosition:UITableViewScrollPositionMiddle  animated:NO]

5.給定寬度和字體大小計算字符串的高度

- (CGSize)getHeightText:(NSString*)text
{
    NSDictionary *attribute = @{NSFontAttributeName: [UIFont systemFontOfSize:14]};
    CGSize size = [text boundingRectWithSize:CGSizeMake(kWindowW-COMMON_CARD_MARGIN*2-105, MAXFLOAT) options: NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attribute context:nil].size;
 
    return size;
}

6.檢測是否是手機號碼

-(BOOL)isMobileNumber:(NSString*)mobileNum
{
//手機號碼
//移動:134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
//聯通:130,131,132,152,155,156,185,186
//電信:133,1349,153,180,189
NSString*MOBILE=@"^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$";
    
 //中國移動:China Mobile
NSString*CM=@"^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$";
    
    
    // 中國聯通:China Unicom
NSString*CU=@"^1(3[0-2]|5[256]|8[56])\\d{8}$";
    
    // 中國電信:China Telecom
NSString*CT=@"^1((33|53|8[09])[0-9]|349)\\d{7}$";
    
  // 大陸地區固話及小靈通
// NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
    
    
    NSPredicate*regextestmobile=[NSPredicate predicateWithFormat:@"SELF MATCHES %@",MOBILE];
    NSPredicate*regextestcm=[NSPredicate predicateWithFormat:@"SELF MATCHES %@",CM];
    NSPredicate*regextestcu=[NSPredicate predicateWithFormat:@"SELF MATCHES %@",CU];
    NSPredicate*regextestct=[NSPredicate predicateWithFormat:@"SELF MATCHES %@",CT];
    if(([regextestmobile evaluateWithObject:mobileNum]==YES)||([regextestcm evaluateWithObject:mobileNum]==YES)||([regextestct evaluateWithObject:mobileNum]==YES)||([regextestcu evaluateWithObject:mobileNum]==YES)){
    return YES;
        }else{
    return NO;
    }
}

7.怎么畫虛線

 - (instancetype)initWithFrame:(CGRect)frame
{
    
    if (self = [super initWithFrame:frame]) {
        [self drawRect:frame];
    }
    return self;
    
}

-(void)drawRect:(CGRect)rect{
    //    self.layer.cornerRadius = 10;
    
    UIView *lineView = [[UIView alloc]init];
    lineView.frame = CGRectMake(12, rect.size.height-1,rect.size.width-12*2, 1);
    
    [DashedLineView drawDashLine:lineView lineLength:4 lineSpacing:3
                 lineColor:kRTColorWithHEX(0xd0d0d0, 1.0)];
    [self addSubview:lineView];
    
    
}

/**
 ** lineView:      需要繪制成虛線的view
 ** lineLength:  虛線的寬度
 ** lineSpacing:    虛線的間距
 ** lineColor:    虛線的顏色
 **/
+ (void)drawDashLine:(UIView *)lineView lineLength:(int)lineLength lineSpacing:(int)lineSpacing lineColor:(UIColor *)lineColor
{
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    [shapeLayer setBounds:lineView.bounds];
    [shapeLayer setPosition:CGPointMake(CGRectGetWidth(lineView.frame) / 2, CGRectGetHeight(lineView.frame))];
    [shapeLayer setFillColor:[UIColor clearColor].CGColor];
    //  設置虛線顏色為blackColor
    [shapeLayer setStrokeColor:lineColor.CGColor];
    //  設置虛線寬度
    [shapeLayer setLineWidth:CGRectGetHeight(lineView.frame)];
    [shapeLayer setLineJoin:kCALineJoinRound];
    //  設置線寬,線間距
    [shapeLayer setLineDashPattern:[NSArray arrayWithObjects:[NSNumber numberWithInt:lineLength], [NSNumber numberWithInt:lineSpacing], nil]];
    //  設置路徑
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathMoveToPoint(path, NULL, 0, 0);
    CGPathAddLineToPoint(path, NULL, CGRectGetWidth(lineView.frame), 0);
    [shapeLayer setPath:path];
    CGPathRelease(path);
    //  把繪制好的虛線添加上來
    [lineView.layer addSublayer:shapeLayer];
}```   

8.把圖片保存到相冊中

- (void)save:(UIBarButtonItem *)sender {
  UIGraphicsBeginImageContext(self.hmView.bounds.size);
  CGContextRef ctx = UIGraphicsGetCurrentContext();
  [self.hmView.layer renderInContext:ctx];
  UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();
  UIImageWriteToSavedPhotosAlbum(image, NULL, NULL, NULL);

}

9.創建單一顏色的圖片然后設置UIControlStateHighlighted狀態

- (UImage *)imageWithColor:(UIColor *)color size:(CGSize)size {
  CGRect rect = CGRectMake(0, 0, size.width, size.height);
  UIGraphicsBeginImageContext(rect.size);
  CGContextRef context = UIGraphicsGetCurrentContext();
  CGContextSetFillColorWithColor(context, [color CGColor]);
   CGContextFillRect(context, rect);
  UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();
  return image;
  }

10.UIView中的坐標轉換

// 將像素point由point所在視圖轉換到目標視圖view中,返回在目標視圖view中的像素值  
  - (CGPoint)convertPoint:(CGPoint)point toView:(UIView *)view;  
    // 將像素point從view中轉換到當前視圖中,返回在當前視圖中的像素值  
    - (CGPoint)convertPoint:(CGPoint)point fromView:(UIView *)view;  
      
    // 將rect由rect所在視圖轉換到目標視圖view中,返回在目標視圖view中的rect  
    - (CGRect)convertRect:(CGRect)rect toView:(UIView *)view;  
    // 將rect從view中轉換到當前視圖中,返回在當前視圖中的rect  
    - (CGRect)convertRect:(CGRect)rect fromView:(UIView *)view;  
    // controllerA 中有一個UITableView, UITableView里有多行UITableVieCell,cell上放有一個button  
    // 在controllerA中實現:  
    CGRect rc = [cell convertRect:cell.btn.frame toView:self.view];  
    或  
    CGRect rc = [self.view convertRect:cell.btn.frame fromView:cell];  
    // 此rc為btn在controllerA中的rect  
      
    或當已知btn時:  
    CGRect rc = [btn.superview convertRect:btn.frame toView:self.view];  
    或  
    CGRect rc = [self.view convertRect:btn.frame fromView:btn.superview]; 

11.顏色:rgb,和16進制

    # define kRTColorWihRGB(R,G,B)     [UIColor colorWithRed:R/255.0 green:G/255.0 blue:B/255.0 alpha:1.0]
    
    # define kRTColorWithHEX(hex,opa)  [UIColor colorWithRed:((float)((hex & 0XFF0000)>>16))/255.0 green:((float)((hex & 0X00FF00)>>8))/255.0 blue:((float)(hex & 0X0000FF))/255.0 alpha:opa]

12.把數據變成三位加逗號的數據類型

  • -(NSString *)formatNumber:(double)num{
    NSNumberFormatter *formatterCurrency = [[NSNumberFormatter alloc] init];
    formatterCurrency.numberStyle = NSNumberFormatterDecimalStyle;
    [formatterCurrency setMaximumFractionDigits:2];
    return [formatterCurrency stringFromNumber: @(num)];
    }
    

13. 把科學計數法變為普通數

    NSString *str = @"1.2808245E7";
        NSRange eSite = [str rangeOfString:@"E"];
        double fund = [[str substringWithRange:NSMakeRange(0, eSite.location)] doubleValue];  //把E前面的數截取下來當底數
        double top = [[str substringFromIndex:eSite.location + 1] doubleValue];   //把E后面的數截取下來當指數
        double result = fund * pow(10.0, top);
    }

14.一些判斷的方法

-(BOOL) isKindOfClass: classObj 用來判斷是否是某個類或其子類的實例
-(BOOL) isMemberOfClass: classObj 用來判斷是否是某個類的實例
-(BOOL) respondsToSelector: selector 用來判斷是否有以某個名字命名的方法(被封裝在一個selector的對象里傳遞)
+(BOOL) instancesRespondToSelector: selector 用來判斷實例是否有以某個名字命名的方法. 和上面一個不同之處在于, 前面這個方法可以用在實例和類上,而此方法只能用在類上.

15.UIDatePicker的簡單使用

 UIDatePicker *dp = [[UIDatePicker alloc] init];
     [dp setDate:[NSDate date] animated:YES];    // 設置日期控件值
     [dp addTarget:self
            action:@selector(dateValueChange:)
  forControlEvents:UIControlEventValueChanged];  // 時間改變時觸發此事件
     設置日期選擇控件的地區
[dp setLocale:[[NSLocale alloc]initWithLocaleIdentifier:@"zh_CN"]];
     NSDateFormatter *form = [[NSDateFormatter alloc] init]; // 定義時間       格式
     [form setDateFormat:@"yyyy/MM/DD HH:mm"];
     NSString *dateString = [form stringFromDate:dp.date];
     dp.minuteInterval = 30; //  最小間隔30分鐘

 dp.minimumDate = [NSDate date];     // 最小值
 dp.maximumDate = [NSDate dateWithTimeIntervalSinceNow:60*60*24*31]; // 最大值
 dp.datePickerMode = UIDatePickerModeTime;               // 時間模式
 dp.datePickerMode = UIDatePickerModeDate;               // 日期模式
 dp.datePickerMode = UIDatePickerModeDateAndTime;        // 日期和時  間模式
  dp.datePickerMode = UIDatePickerModeCountDownTimer;     // 倒計時模式

16 ,計算據今天兩個月的日期

   //創建日歷
  NSCalendar *calendar = [NSCalendar currentCalendar];
        NSDateComponents *com = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:[NSDate date]];
        com.year = 0;
        com.month = 2;
        com.day = 0;
  NSDate *date = [calendar dateByAddingComponents:com toDate:[NSDate date]options:0];

17 ,導航的問題

  • - (void)initNavigationBar:(UINavigationBar *)navigationBar{
    
    // 設置導航欄的背景顏色
    UIColor* backgroundColor = [UIColor colorWithRed:(float)0x20/0xff green:(float)0x24/0xff blue:(float)0x2c/0xff alpha:1.0];
    [navigationBar setTranslucent:NO];
    [navigationBar setBarTintColor:backgroundColor];
    [navigationBar setBackgroundColor:backgroundColor];
    
    // 設置導航欄上的標題的顏色 
    navigationBar.titleTextAttributes = @{NSFontAttributeName:[UIFont systemFontOfSize:18],NSForegroundColorAttributeName:kRTColorWithHEX(0xffffff, 1)};   
    for (UINavigationItem *item in [navigationBar items]) {
        item.leftBarButtonItem.tintColor =[UIColor whiteColor];
    }
    
    // 去掉導航欄的邊界線
    [navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
    navigationBar.shadowImage = [[UIImage alloc] init];
    }
    

    創建block匿名函數之前一般需要對self進行weak化,否則造成循環引用無法釋放controller:

    __weak MyController *weakSelf = self 或者 __weak __typeof(self) weakSelf = self;

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,837評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,196評論 3 414
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,688評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,654評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,456評論 6 406
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 54,955評論 1 321
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,044評論 3 440
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,195評論 0 287
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,725評論 1 333
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,608評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,802評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,318評論 5 358
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,048評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,422評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,673評論 1 281
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,424評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,762評論 2 372

推薦閱讀更多精彩內容